http://www.jb51.net/article/99457.htm
图片在系统中的存在形式:
- 文件形式:file(即以二进制形式存在于硬盘上)
- 流:stream(即以二进制形式存在于内存中)
- Bitmap 对象
检测图片三种形式大小的方法:
- 文件形式: file.length()
- 流的形式: 讲图片文件读到内存输入流中,看它的 byte 数
- Bitmap: bitmap.getByteCount()
Android中图片有四种属性,分别是:
ALPHA_8:每个像素占用1byte内存
ARGB_4444:每个像素占用2byte内存
ARGB_8888:每个像素占用4byte内存 (默认)
RGB_565:每个像素占用2byte内存
Android默认的颜色模式为ARGB_8888,这个颜色模式色彩最细腻,显示质量最高。但同样的,占用的内存也最大。 所以在对图片效果不是特别高的情况下使用RGB_565(565没有透明度属性)
BitmapFactory 解析方式:
decodeFile
decodeFileDescriptor
decodeStream
decodeResource
decodeByteArray
压缩方法:
- 将图片保存到本地时进行压缩, 即将图片从Bitmap形式变为File形式时进行压缩,
特点是: File形式的图片确实被压缩了, 但是当你重新读取压缩后的file为 Bitmap是,它占用的内存并没有改变。方法说明: 该方法是压缩图片的质量, 注意它不会减少图片的像素。
public static void compressBmpToFile(Bitmap bmp,File file){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int options = 80;//个人喜欢从80开始,
bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);
while (baos.toByteArray().length / 1024 > 100) {
baos.reset();
options -= 10;
bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);
}
try {
FileOutputStream fos = new FileOutputStream(file);
fos.write(baos.toByteArray());
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
- 将图片从本地读到内存时,进行压缩 ,即图片从File形式变为Bitmap形式
特点: 通过设置采样率, 减少图片的像素, 达到对内存中的Bitmap进行压缩
方法说明: 该方法就是对Bitmap形式的图片进行压缩, 也就是通过设置采样率, 减少Bitmap的像素, 从而减少了它所占用的内存
private Bitmap compressImageFromFile(String srcPath) {
BitmapFactory.Options newOpts = new BitmapFactory.Options();
newOpts.inJustDecodeBounds = true;//只读边,不读内容
Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
newOpts.inJustDecodeBounds = false;
int w = newOpts.outWidth;
int h = newOpts.outHeight;
float hh = 800f;//
float ww = 480f;//
int be = 1;
if (w > h && w > ww) {
be = (int) (newOpts.outWidth / ww);
} else if (w < h && h > hh) {
be = (int) (newOpts.outHeight / hh);
}
if (be <= 0)
be = 1;
newOpts.inSampleSize = be;//设置采样率
newOpts.inPreferredConfig = Config.ARGB_8888;//该模式是默认的,可不设
newOpts.inPurgeable = true;// 同时设置才会有效
newOpts.inInputShareable = true;//。当系统内存不够时候图片自动被回收
bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
// return compressBmpFromBmp(bitmap);//原来的方法调用了这个方法企图进行二次压缩
//其实是无效的,大家尽管尝试
return bitmap;
}