您的位置:首页 > 移动开发 > Android开发

Android_Bitmap压缩杂谈

2015-12-15 17:12 344 查看
情况一:图片太大,因为手机资源的稀缺,如果每个图片都很大,很容易出现OOM的情况。所以,适当对图片的质量进行压缩还是有必要的。

实习代码如下:

private Bitmap compressImage(Bitmap image) {

ByteArrayOutputStream target_baos= new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, target_baos);//质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
int options = 100;
while ( target_baos.toByteArray().length / 1024>100) { //循环判断如果压缩后图片是否大于100kb,大于继续压缩
target_baos.reset();//重置baos即清空baos
image.compress(Bitmap.CompressFormat.JPEG, options, target_baos);//这里压缩options%,把压缩后的数据存放到baos中
options -= 10;//每次都减少10
}
ByteArrayInputStream isBm = new ByteArrayInputStream(target_baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中
Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片
return bitmap;
}


通过如上方法可以将Bitmap大小进行压缩,有利于APP的内存利用。

情况二:图片尺寸过大,将Bitmap缩放适当尺寸,已完成不同屏幕的适配。

方法1:利用矩阵缩放,代码如下:

//获取屏幕的宽高
DisplayMetrics metrics = new DisplayMetrics();
((Activity)context).getWindowManager().getDefaultDisplay().getMetrics(metrics);
int width = metrics.widthPixels;
int height = metrics.heightPixels;
//标准尺寸屏幕的比例关系,计算出该屏幕下图片的尺寸,并设置一个最大值,放置在另类手机适配出现问题。
int cellWidth = (int)((180.0f/1080.0f)*width);
if (cellWidth >240)
cellWidth = 240;
int bitmapWidth = getBitmapFor(R.mipmap.pointer_pw).getWidth();
int bitmapHeight = getBitmapFor(R.mipmap.pointer_pw).getHeight();
float scale = (float)cellWidth/(float)bitmapWidth;//根据目标尺寸和原始图片尺寸计算比例
Matrix matrix = new Matrix();
matrix.postScale(scale,scale);

// 得出最后的bitmap
mBitmapBtnDefault = Bitmap.createBitmap(getBitmapFor(R.mipmap.pointer_pw),0,0,bitmapWidth,bitmapHeight,matrix,true);

方法2:利用BitmapFactory.Options 完成缩放
private Bitmap getimage(String srcPath) {
BitmapFactory.Options newOpts = new BitmapFactory.Options();
//开始读入图片,此时把options.inJustDecodeBounds 设回true了
newOpts.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeFile(srcPath,newOpts);//此时返回bm为空

newOpts.inJustDecodeBounds = false;
int factor = 4;
newOpts.inSampleSize = factor;//设置缩放比例,实际为所设值得倒数
//重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了
bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
return bitmap;//压缩好比例大小后再进行质量压缩
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  位图 Bitmap Android 压缩