图片压缩总结
一、图片存储形式
1、文件形式(以二进制储形式存在硬盘上)
2、流形式(以二进制形式储存在内存中)
3、Bitmap形式(数据会远远大于以上两种形式)
一、常见的压缩方式
1、将图片保存到本地时压缩,保存为File文件
特点:File形式的图片被压缩了,但是当你重新读取后获得Bitmap是没有改变的,改变的只是图片的显示质量。
public static void compressBmpToFile(Bitmapbmp,File file){
ByteArrayOutputStream baos = newByteArrayOutputStream();
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 = newFileOutputStream(file);
fos.write(baos.toByteArray());
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
二、将图片从本地读到内存时,进行压缩,即图片从File形式变为Bitmap形式
特点: 通过设置采样率, 减少图片的像素, 达到对内存中的Bitmap进行压缩
private Bitmap compressImageFromFile(StringsrcPath) {
BitmapFactory.Options newOpts = newBitmapFactory.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);
// returncompressBmpFromBmp(bitmap);//原来的方法调用了这个方法企图进行二次压缩
//其实是无效的,大家尽管尝试
return bitmap;
}