标签:压缩 图片 bitmapfactory
在进行图片压缩时,是通过设置BitmapFactory.Options的一些值来改变图片的属性的,下面我们来看看BitmapFactory.Options中常用的属性意思:
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeResource(getResource(), R.mipmap.two, options);
Log.v("zxy","bitmap="+bitmap);
int height = options.outHeight;
int width = options.outWidth;
String mimeType = options.outMimeType;
Log.v("zxy","mimeType="+mimeType+",height="+height+",width="+width);上述代码输出的是:public class MainActivity extends ActionBarActivity {
private ImageView mImageView, mResizeImageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mImageView = (ImageView) findViewById(R.id.imageView);
mResizeImageView = (ImageView) findViewById(R.id.resize_imageView);
mImageView.setImageBitmap(BitmapFactory.decodeResource(getResources(),R.mipmap.two));
Bitmap bitmap = compressBitmap(getResources(), R.mipmap.two, 100, 100);
Log.v("zxy", "compressBitmap,width=" + bitmap.getWidth() + ",height=" + bitmap.getHeight());
mResizeImageView.setImageBitmap(bitmap);
}
/**
* @param res Resource
* @param resId 资源id
* @param targetWidth 目标图片的宽,单位px
* @param targetHeight 目标图片的高,单位px
* @return 返回压缩后的图片的Bitmap
*/
public Bitmap compressBitmap(Resources res, int resId, int targetWidth, int targetHeight) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;//设为true,节约内存
BitmapFactory.decodeResource(res, resId, options);//返回null
int height = options.outHeight;//得到源图片height,单位px
int width = options.outWidth;//得到源图片的width,单位px
//计算inSampleSize
options.inSampleSize = calculateInSampleSize(width,height,targetWidth,targetHeight);
options.inJustDecodeBounds = false;//设为false,可以返回Bitmap
return BitmapFactory.decodeResource(res,resId,options);
}
/**
* 计算压缩比例
* @param width 源图片的宽
* @param height 源图片的高
* @param targetWidth 目标图片的宽
* @param targetHeight 目标图片的高
* @return inSampleSize 压缩比例
*/
public int calculateInSampleSize(int width,int height, int targetWidth, int targetHeight) {
int inSampleSize = 1;
if (height > targetHeight || width > targetWidth) {
//计算图片实际的宽高和目标图片宽高的比率
final int heightRate = Math.round((float) height / (float) targetHeight);
final int widthRate = Math.round((float) width / (float) targetWidth);
//选取最小的比率作为inSampleSize
inSampleSize = heightRate < widthRate ? heightRate : widthRate;
}
return inSampleSize;
}
}我们通过看Log可以知道压缩后图片的宽高:
我们再看看效果图:
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:压缩 图片 bitmapfactory
原文地址:http://blog.csdn.net/u010687392/article/details/46999719