美文网首页
加载bitmap时压缩,减小OOM可能性。

加载bitmap时压缩,减小OOM可能性。

作者: 黑曼巴_e5b9 | 来源:发表于2019-04-18 15:46 被阅读0次

Bitmap在Android中指的是一张图片。通过BitmapFactory类提供的四类方法:decodeFile,decodeResource,decodeStream和decodeByteArray,分别从文件系统,资源,输入流和字节数组中加载出一个Bitmap对象。

本文以decodeResource方式说明。


public BitmapdecodeBitmap(int width, int height) {

BitmapFactory.Options op =new BitmapFactory.Options();

    op.inJustDecodeBounds =true;//获取bitmap的原始宽高信息,不生成bitmap

    Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.mipmap.test, op);

    int originalWidth = op.outWidth;

    int originalHeight = op.outHeight;

    op.inJustDecodeBounds =false;//根据采样率真正生成压缩后的bitmap

    op.inSampleSize = getSampleSize(originalWidth, originalHeight, width, height);

    Bitmap bitmap1 = BitmapFactory.decodeResource(context.getResources(), R.mipmap.test, op);

    Log.d("bitmapUtil", "bitmap: " + bitmap1.getByteCount());

    return bitmap1;

}

private int getSampleSize(int originalWidth, int originalHeight, int width, int height) {

// 初始化采样率

    int sampleSize =1;

    if (originalWidth > originalHeight && originalWidth > width) {

Log.d("bitmapUtil", "originalwidth: " + originalWidth);

        Log.d("bitmapUtil", "width: " + width);

        // 用宽度计算采样率

        sampleSize = originalWidth / width;

    }else if (originalWidth < originalHeight && originalHeight > height) {

Log.d("bitmapUtil", "originalHeight: " + originalHeight);

        Log.d("bitmapUtil", "height: " + height);

        // 用高度计算采样率

        sampleSize = originalHeight / height;

    }

if (sampleSize <=0) {

sampleSize =1;

    }

return sampleSize;

}

相关文章

网友评论

      本文标题:加载bitmap时压缩,减小OOM可能性。

      本文链接:https://www.haomeiwen.com/subject/xwdtgqtx.html