图片转换工具类BitmapFactory的使用

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 实例,达到了图片压缩的效果

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值