这几天做的项目中有个图片上传模块,上传部分用的是xutils框架上传前自动对图片进行了压缩处理。但用户还是一直反应上传特别慢,主要是因为现在手机一般一张图片都特别大,没处理或者处理不够的话会严重影响用户体验,于是研究了下Android的图片压缩部分:
一:图片压缩相关的概念(参考:http://blog.csdn.net/cherry609195946/article/details/9264409)
1.Android中图片的存在形式有三种:
a.File的形式存在于硬盘中。
b.在内存中存在有两种形式,一种是流,一种是bitmap
2.广义所说的图片压缩包括两种方式:质量压缩和大小压缩
质量压缩:通说说就是将图片保存为File时候进行压缩,让其大小变小。主要用在网络上传图片时候方便上传服务器。但其内存中大小并未改变,甚至 会变大。
大小压缩:图片从本地读取时候转换成bitmap过程中进行压缩处理,通过设置采样率减少图片的像素,达到对内存中bitmap进行压缩,减少占用内存
二:压缩部分的代码
质量压缩:
<span style="font-size:14px;">private Bitmap compressImage(Bitmap image) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
int options = 100;
while ( baos.toByteArray().length / 1024>100) { //循环判断如果压缩后图片是否大于100kb,大于继续压缩
baos.reset();//重置baos即清空baos
options -= 10;//每次都减少10
image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%,把压缩后的数据存放到baos中
}
ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中
Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片
return bitmap;
//返回的bitmap所占内存并没减少。。
// Generate compressed image file 保存成File形式
FileOutputStream fos = new FileOutputStream(outPath);
fos.write(os.toByteArray());
fos.flush();
fos.close();
}</span>
大小压缩;
a.计算压缩比例
<span style="font-size:14px;">public static int calculateInSampleSize(BitmapFactory.Options options,int reqWidth, int reqHeight) {
final int height = options.outHeight; //图片的原始高 宽
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int heightRatio = Math.round((float) height/ (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}</span>
b.开始压缩
// 根据路径获得图片并压缩,返回bitmap用于显示
<span style="font-size:14px;"> public static Bitmap getSmallBitmap(String filePath) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
//inJustDecodeBounds设置为true,可以不把图片读到内存中,但依然可以计算出图片的大小
BitmapFactory.decodeFile(filePath, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, 480, 800);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
//此时返回的就是已经被压缩的bitmap。。可以用于显示在界面上
return BitmapFactory.decodeFile(filePath, options);
}</span>
总结:一般图片压缩处理是先进行大小压缩,在进行质量压缩相互结合方式。
Thanks:
http://www.360doc.com/content/14/0428/17/11800748_372972179.shtml