首页 > Android ImageView问题

Android ImageView问题

使用Android Studio进行安卓开发的时候,在ImageView里放一张400K的图片,爆出了OOM错误,求大神指教,不想把图片压缩,况且400K图片也并不大


你看着图片是 400K ,那是图片压缩后的大小,图片占用的内存不是他在硬盘里躺着的时候的内存。
图片内存占用请用 图片宽度 x 图片高度 x 4 Byte 来进行计算。

你这一下申请了 100 多 MB 的内存,这图高宽至少都是 5000 像素,你这还不缩放一下还想干嘛……


解码Bitmap时设置有问题。下面这篇博文,详细介绍Bitmap数据时如何decode进内存,怎样避免OOM
Android 开发绕不过的坑:你的 Bitmap 究竟占多大内存?


大图载入,可以尝试利用局部加载的方式,SubsamplingScaleImageView github应该有这么一个开源项目能满足需求,不会因为图片过大而产生OOM。FaceBook的Fresco也是不错的选择,不过这个功能就比较重了。

以上各个楼的回答是显示图片在一屏幕以内的方式,就是尽量所见即所得。不过如果你的目的就是载入一张长宽很大的图片,例如世界地图之类的的话建议采用我说的第一个开源项目效果不错,拓展性也不错。


400K图片已经炸了。。。

 public static int calculateInSampleSize(BitmapFactory.Options options,
                                            int reqWidth, int reqHeight) {
        // 源图片的高度和宽度
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;
        if (height > reqHeight || width > reqWidth) {
            // 计算出实际宽高和目标宽高的比率
            final int heightRatio = Math.round((float) height / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
            // 选择宽和高中最小的比率作为inSampleSize的值,这样可以保证最终图片的宽和高
            // 一定都会大于等于目标的宽和高。
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }
        return inSampleSize;
    }

    public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
                                                         int reqWidth, int reqHeight) {
        // 第一次解析将inJustDecodeBounds设置为true,来获取图片大小
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(res, resId, options);
        // 调用上面定义的方法计算inSampleSize值
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
        // 使用获取到的inSampleSize值再次解析图片
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeResource(res, resId, options);
    }

在第二段代码参数中输入imageView大小合适的宽高就了

【热门文章】
【热门文章】