• 高效载入“大”图片


    高效载入图片方式:

    设置的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

    为什么会出现上述情况?

  • 相关阅读:
    冲刺第五天个人博客
    冲刺第四天个人博客
    典型用户及场景
    冲刺第三天个人博客
    冲刺第二天个人博客
    冲刺第一天个人博客
    第三周学习进度表
    第二周学习进度表
    webServices
    vs开发工具使用问题
  • 原文地址:https://www.cnblogs.com/CVstyle/p/6388113.html
Copyright © 2020-2023  润新知