Bootstrap

使用BitmapFactory压缩图片遇到的问题总结

压缩前先搞明白原理:Bitmap占用的内存大小:

bytes = 原始图片宽*(options.inTargetDensity/options.inDensity)*原始图片长*(options.inTargetDensity/options.inDensity)*每个像素点位数

inTargetDensity指的是当前手机的密度,inDensity是图片的所在drawable目录生成的密度

使用sample采样率来对Bitmap进行压缩到指定的宽和高(原理不在赘述)
方法相信大家都熟悉,网上一搜都大体类似,下面是具体的方法

// 使用decodeRes方法对资源进行转换,使用InJustDecodeBounds属性置为true,先获图
//片高,native层先不返回Bitmap
//进行计算sampleSize,然后设为false,再次decode返回Bitmap
public Bitmap compressBitmapIntoThumbnailPic(Context context, int res) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        Bitmap bitmap1 = BitmapFactory.decodeResource(context.getResources(), res, options);
        Log.d("tag", "first bitmap == " + bitmap1);
        int sampleBitmap = calculateInSampleSize(options, 40, 40);
        options.inSampleSize = sampleBitmap;
        options.inJustDecodeBounds = false;
        Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), res, options);
        Log.d("tag", "final == " + bitmap.getByteCount() +
                " target real density  " + options.inTargetDensity + " folder density " + options.inDensity);
        return bitmap;
    }
// 对要求的宽高和当前图片宽高对比,取一个最小的比例作为sampleSize
 private int calculateInSampleSize(BitmapFactory.Options options, int requireW, int requereH) {
        int sampleSize = 1;
        int outHeight = options.outHeight;
        int outWidth = options.outWidth;
        int rationHeight = Math.round(outHeight / requereH);
        int rationWidth = Math.round(outWidth / requireW);
        if (rationHeight > 1 || rationWidth > 1) {
            sampleSize = rationHeight > rationWidth ? rationWidth : rationHeight;
        }
        Log.d(
;