Android高效加载大图

通过BitmapFactorydecode方法设置特定的options缩小图片到指定尺寸

  • 1:通过加载设置了只编码图片边界options的图片,获取原图的尺寸和类型
  • 2:计算图片需要缩小的倍数
  • 3:设置options的inSimpleSize属性为缩小的倍数
  • 4:获取缩小之后的Bitmap

options.inJustDecodeBounds = true;
设置会在decode时,不分配内存,但是可以获取图片的尺寸和类型

options.inSampleSize属性设置图片的缩小倍数

If set to a value > 1, requests the decoder to subsample the original image, returning a smaller image to save memory.The sample size is the number of pixels in either dimension that correspond to a single pixel in the decoded bitmap. For example, inSampleSize == 4 returns an image that is 1/4 the width/height of the original, and 1/16 the number of pixels. Any value <= 1 is treated the same as 1. Note: the decoder uses a final value based on powers of 2, any other value will be rounded down to the nearest power of 2.

如果设置的值大于1,解码器就会从原始图片中抽取返回一个缩小的图片储存在内存中。这个SimpleSize值是每个维度中的像素数,对应于被解码的图片的单个像素。例如,SimpleSize==4,就会返回一个宽或高是原图1/4的图片,像素则是原图的1/16。小于1的值相当于1。解码器使用基于2的幂的数值,对于任何SimpleSize不是2的幂的值都会被和谐到最接近2的值。

public class BitmapTool {

    //读取图片尺寸和类型
    private static BitmapFactory.Options getBitmapOptionsOnlyWidthAndHeight(String imagePath) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        //设置为true之后,decode**方法将会不分配内存,但是可以获取图片的宽高,类型
        options.inJustDecodeBounds = true;  //just decode bounds意味这只加载边界
        BitmapFactory.decodeFile(imagePath, options);
        return options;
    }

    //获取图片应该被缩小的倍数
    private static int getScaleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        final int imageWidth = options.outWidth;
        final int imageHeight = options.outHeight;
        int scaleSize = 1;

        //如果图片的实际尺寸大于了实际需要的,就计算缩放倍数
        if (imageWidth > reqWidth || imageHeight > reqHeight) {
            final int halfWidth = imageWidth / 2;
            final int halfHeight = imageHeight / 2;

            while ((halfWidth / scaleSize) > reqWidth && (halfHeight / scaleSize) > reqHeight) {
                scaleSize *= 2;
            }
        }
        return scaleSize;
    }


    /**
     * 从资源中加载图片
     *
     * @param reqWidth  目标宽
     * @param reqHeight 目标高
     * @return 缩小之后的图片
     */
    public static Bitmap getBitmapFromResource(Context context, int id, int reqWidth, int reqHeight) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        //设置为true之后,decode**方法将会不分配内存,但是可以获取图片的宽高,类型
        options.inJustDecodeBounds = true;  //just decode bounds意味这只加载边界
        BitmapFactory.decodeResource(context.getResources(), id, options);
        options.inSampleSize = getScaleSize(options, reqWidth, reqHeight);
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeResource(context.getResources(), id, options);
    }
}
posted @ 2017-08-03 21:39  just_yang  阅读(520)  评论(0编辑  收藏  举报