您的位置:首页 > 其它

图片转换工具类BitmapFactory的使用

2016-05-25 14:26 267 查看
BitmpaFactory:android提供的一个工具类,可以将不同资源(如:文件 files、流 Streams、字节数组 byte-arrays、drawable下的图片资源)转换成Bitmap。

该类分别提供了方法对各种资源进行转换:decodeFile、decodeStream、decodeResource、decodeByteArray

`public static Bitmap decodeResource(Resources res, int id) {
return decodeResource(res, id, null);
}
`
`public static Bitmap decodeFile(String pathName) {
return decodeFile(pathName, null);
}`
`public static Bitmap decodeStream(InputStream is) {
return decodeStream(is, null, null);
}`
`public static Bitmap decodeByteArray(byte[] data, int offset, int length) {
return decodeByteArray(data, offset, length, null);
}`


同时,BitmapFactory工具类中还定义了一个 Options 类,该类的主要功能是可以对转换成的Bitmap对象进行压缩处理:

其中,Options类中的inSampleSize属性就是图片采样大小,我们可以根据这个属性设置我们需要对图片压缩的比例,如下所示:

`BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true; //不加载图片进内存,只获取图片宽高
//此时,返回的Bitmap实体为null,只有Bitmap的宽高,
BitmapFactory.decodeFile(mPhotoFile.getAbsolutePath(), options);
options.inSampleSize = calculateInSampleSize(options, 100, 80);
options.inPurgeable = true;
options.inJustDecodeBounds = false;
//对图片进行压缩
Bitmap bitmap = BitmapFactory.decodeFile(mPhotoFile.getAbsolutePath(), options);
Log.e("bitmap", "图片压缩后的高度:" + bitmap.getHeight() +"   "+ "图片压缩后的宽度:" + bitmap.getWidth());
mImageView.setImageBitmap(bitmap);
}

/**
* 计算图片的压缩采样比例大小
*
* @param options
* @param reqWidth
* @param reqHeight
* @return
*/
private int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
int width = options.outWidth;
int height = options.outHeight;
Log.e("bitmap", "outHeight:" + height + "outWidth:" + width);
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
int halHeight = height / 2;
int halWidth = width / 2;
while ((halHeight / inSampleSize) > reqHeight
&& (halWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}`


其中,可以看到 options.inJustDecodeBounds 这个属性;当我们要获取图片的宽高时,为了避免内存的消耗,我们一般将该属性设置为 true,表示不将图片加载进内存,只获取图片的宽高,然后将 options 实例保存到BitmapFactory中,再进行对 options 实例属性的设定:如 inSampleSize,最后将修改后的 options 重新赋值到BitmapFactory中,覆盖掉原来的options 实例,达到了图片压缩的效果
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: