图片加载出现OOM
setBackgroundResource加载图片的额时候。会出现错误。
private final int[] imageIds = { R.mipmap.a, R.mipmap.b, R.mipmap.c,
R.mipmap.d, R.mipmap.e };
ImageView image = new ImageView(this);
image.setBackgroundResource(imageIds[i]);//这儿会出现OOM错误。
imageList.add(image);
错误如下:Java.lang.OutOfMemoryError: Failed to allocate a 8487512 byte allocation with 4194304 free bytes and 6MB until OOM
Throwing OutOfMemoryError “Failed to allocate a 8487512 byte allocation with 4194304 free bytes and 6MB until OOM”
allocation failed for scaled bitmap
at Android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
04-16 04:42:19.465 2703-2703/? E/AndroidRuntime: at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:609)
04-16 04:42:19.465 2703-2703/? E/AndroidRuntime: at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:444)
04-16 04:42:19.465 2703-2703/? E/AndroidRuntime: at android.graphics.BitmapFactory.decodeResource(BitmapFactory.java:467)
04-16 04:42:19.465 2703-2703/? E/AndroidRuntime: at android.graphics.BitmapFactory.decodeResource(BitmapFactory.java:497)
出现问题的原因是;图片加载过大,建议大家使用库来完成图片的加载,setBackgroundResource的时候要转换为bitmap,要求的内存太多,当前系统无法满足
网上很多教程,百度 图片放缩。
下面附加一个不带库的。
ImageView image = new ImageView(this);
// image.setBackgroundResource(imageIds[i]);
//////////////
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inPreferredConfig = Bitmap.Config.RGB_565;
opt.inPurgeable = true;
opt.inInputShareable = true;
InputStream is = getResources().openRawResource(
imageIds[i] );
Bitmap bm = BitmapFactory.decodeStream(is, null, opt);
BitmapDrawable bd = new BitmapDrawable(getResources(), bm);
image.setBackgroundDrawable(bd);
// BitmapFactory.decodeResource(getResources(),imageIds)
imageList.add(image);