今天用ImageView加载图片时,图片并不能显示,logcat中打印出了 Bitmap too large to be uploaded into a texture (4160x3120, max=4096x4096)的错误提示。
在网上搜索了一番,因为当开启硬件加速的时候,GPU对于openglRender 有一个限制,这个不同的手机会有不同的限制:
这个限制值可以通过canvas.getMaximumBitmapHeight()和canvas.getMaximumBitmapWidth()来获得。
网上一个简单粗暴的方法是关闭硬件加速:
- <code class="language-html"><application
- android:hardwareAccelerated="false" ></code>
这样的确解决了图片,但你会在app运行的时候,发现app变得十分卡顿。
果断抛弃了这个方法,百度了好久也没找到个像样的解决方案,大多都是东抄西抄,放弃了百度。
认真看看提示,是Bitmap too large 。我突然想起很早很早之前看过郭神的一篇关于加载大图OOM的问题的一篇博客。
我们只要通过BitmapFactory.Options对象对图片进行压缩就好了。废话不多说,我直接在ImageUtil类中写下了图片压缩的方法。
-
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);
-
}
-
-
public static Bitmap decodeSampledBitmapFromFilePath(String imagePath,
-
int reqWidth, int reqHeight) {
-
// 第一次解析将inJustDecodeBounds设置为true,来获取图片大小
-
final BitmapFactory.Options options = new BitmapFactory.Options();
-
options.inJustDecodeBounds = true;
-
BitmapFactory.decodeFile(imagePath, options);
-
// 调用上面定义的方法计算inSampleSize值
-
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
-
// 使用获取到的inSampleSize值再次解析图片
-
options.inJustDecodeBounds = false;
-
return BitmapFactory.decodeFile(imagePath,options);
-
}
然后在需要的地方调用就好了,上面的代码也是直接参考郭神的博客中的代码的,注释已经很清楚了。
最后在需要的地方调用我们的方法:
imageView.setImageBitmap(ImageUtil.decodeSampledBitmapFromFilePath(imagePath,100,100));
通过图片压缩,我们的图片能够被正常的显示了。
希望通过这篇文章,能够帮助遇到Bitmap too large to be uploaded into a texture深陷百度不能自拔的小伙伴能够快速解决。
资料参考:
郭霖 :Android高效加载大图、多图解决方案,有效避免程序OOM
http://blog.csdn.net/sinyu890807/article/details/9316683