Android Bitmap压缩方式分析

在网上调查了图片压缩的方法并实装后,大致上可以认为有两类压缩:质量压缩(不改变图片的尺寸)和尺寸压缩(相当于是像素上的压缩);质量压缩一般可用于上传大图前的处理,这样就可以节省一定的流量,毕竟现在的手机拍照都能达到3M左右了,尺寸压缩一般可用于生成缩略图。
在Android开发中我们都会遇到在一个100*100的ImageView上显示一张过大的图片,如果直接把这张图片显示上去对我们应用没有一点好处反而存在OOM的危险,所以我们有必要采用一种有效压缩方式来显示上去。
private void calculateBitmapInSimpleSize() {
Bitmap _bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.bg_homepage);
getBitmapDatas(_bitmap);
BitmapFactory.Options optioins = new BitmapFactory.Options();
optioins.inJustDecodeBounds = true;
// optioins.inPreferredConfig = Bitmap.Config.RGB_565;//11158560
optioins.inPreferredConfig = Bitmap.Config.ARGB_8888;//22317120
BitmapFactory.decodeResource(getResources(), R.drawable.bg_homepage, optioins);
int reqWidth = optioins.outWidth;
int reqHeight = optioins.outHeight;
Log.w(TAG, "reqWidth = " + reqWidth);
Log.w(TAG, "reqHeight = " + reqHeight);
int inSampleSize = 1;
final int widthRatio = Math.round((float)reqWidth / 100f);
final int heigthRatio = Math.round((float) reqHeight / 100f);
// 取最小值 这将保证压缩出来的图片大于或者等于请求的宽度或者高度
inSampleSize = widthRatio > heigthRatio ? heigthRatio : widthRatio;
Log.w(TAG, "first inSampleSize = " + inSampleSize);
final int totalPixel = 100 * 100;
final int totalReqPixel = reqWidth * reqHeight * 2;
Log.w(TAG, "totalReqPixel = " + totalReqPixel);
while (totalPixel / (inSampleSize * inSampleSize) > totalReqPixel) {
Log.w(TAG, "totalPixel = " + (totalPixel / (inSampleSize * inSampleSize)));
inSampleSize ++;
}
Log.w(TAG, "LastInSampleSize = " + inSampleSize);
optioins.inJustDecodeBounds = false;
Bitmap lastBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.bg_homepage, optioins);
getBitmapDatas(lastBitmap);
mImageView.setImageBitmap(lastBitmap);
}