高效载入“大”图片

高效载入图片方式:

设置的reqWidth和reqHeight并不是最终的图片分辨率,而是一个近似比例。图片根据这个宽度和长度的比例值,计算出最相近的降采样值inSampleSize.

    public static int calculateInSampleSize(BitmapFactory.Options options,
            int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        LogUtil.d(TAG, "calculateInSampleSize::height=" + height + " width="
                + width);
        int inSampleSize = 1;
        if (height > reqHeight || width > reqWidth) {
            final int halfHeight = height / 2;
            final int halfWidth = width / 2;
            while ((halfHeight / inSampleSize) > reqHeight
                    && (halfWidth / inSampleSize) > reqWidth) {
                inSampleSize *= 2;
            }
        }
        LogUtil.d(TAG, "calculateInSampleSize::inSampleSize=" + inSampleSize);
        return inSampleSize;
    }
    public static Bitmap decodeSampleBitmatFromResource(Resources res,
            int resId, int reqWidth, int reqHeight) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        // 不分配内存空间
        options.inJustDecodeBounds = true;
        // options.outHeight和options.outWidth
        BitmapFactory.decodeResource(res, resId, options);
        options.inSampleSize = calculateInSampleSize(options, reqWidth,
                reqHeight);
        // 分配内存空间
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeResource(res, resId, options);
    }

通过设置options.inJustDecodeBounds值,能够选择是否为图片分配内存;也就是在不占用内存的情况下,获取图片信息。

使用drawable方式载入图片,并进行压缩:

Bitmap srcBitmap = UtilTools.decodeSampleBitmatFromResource(
        getResources(), R.drawable.mypng, 100, 100);

图片分辨率:1920*1080(默认为:宽和长),计算获得的压缩比为:8;图片压缩后分辨率为:240*135

使用raw方式载入图片,并进行压缩:

    Bitmap srcBitmap = UtilTools.decodeSampleBitmatFromResource(
            getResources(), R.raw.mypng, 100, 100);

虽图片相同,计算得到的采样也一致;最终获取的图片分辨率却不同:480*270

为什么会出现上述情况?

原文地址:https://www.cnblogs.com/CVstyle/p/6388113.html