【问题标题】:OutofMemoryError while trying to construct Bitmap from byte Array尝试从字节数组构造位图时出现 OutofMemoryError
【发布时间】:2013-05-06 10:32:22
【问题描述】:

我正在从 blob 类型中获取字节数组,而它存储在 db 中,它适用于小图像,但是当图像大小超过 200kb 时,它会给我一个 outofmemoryerror 错误。 我应该怎么做才能克服这样的错误

照片是我的字节数组

ByteArrayInputStream imageStream = new ByteArrayInputStream(photo);
            Bitmap theImage= BitmapFactory.decodeStream(imageStream);
            Bitmap bitmapScaled = Bitmap.createScaledBitmap(theImage, 100,80, true);
            Drawable drawable = new BitmapDrawable(bitmapScaled);
            imgPath.setBackgroundDrawable(drawable);
            imgPath.setScaleType(ImageView.ScaleType.FIT_END);

Logcat 错误

05-06 15:55:38.871: E/AndroidRuntime(2647): FATAL EXCEPTION: main
05-06 15:55:38.871: E/AndroidRuntime(2647): java.lang.OutOfMemoryError
05-06 15:55:38.871: E/AndroidRuntime(2647):     at android.graphics.BitmapFactory.nativeDecodeStream(Native Method)
05-06 15:55:38.871: E/AndroidRuntime(2647):     at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:493)
05-06 15:55:38.871: E/AndroidRuntime(2647):     at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:549)
05-06 15:55:38.871: E/AndroidRuntime(2647):     at com.example.hotelmenu.RevisedMainMenu.displayMenu(RevisedMainMenu.java:655)
05-06 15:55:38.871: E/AndroidRuntime(2647):     at com.example.hotelmenu.RevisedMainMenu.onClick(RevisedMainMenu.java:615)

【问题讨论】:

  • google 和 SO 上有很多建议,你有没有搜索过/

标签: android bitmap android-imageview android-image


【解决方案1】:

图像大小无关紧要。重要的是宽度和高度。事实上,您的 Bitmap 实例将保留 width*height*4 字节。如果您收到OOM,我会建议您对您的Bitmap 进行下采样。

还有

 Bitmap theImage= BitmapFactory.decodeStream(imageStream);
 Bitmap bitmapScaled = Bitmap.createScaledBitmap(theImage, 100,80, true);

在您提供的 sn-p 中,在创建 bitmapScaled 之后,theImage in 从未使用过。你应该循环调用它

theImage.recycle().

编辑。这个 sn-p 将创建一个比原来宽和高 1/4 的位图

 BitmapFactory.Options options=new BitmapFactory.Options();
 options.inSampleSize = 4;
 Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream, null, options );

【讨论】:

  • -blackbelt 好的,你能给我举个例子吗?
  • 例子是什么?下采样位图?
  • 我是新手,我不明白 Downsamplig 这个词。我需要的是如何克服 outofMemory 的这个错误,以及这个错误的原因
  • – 黑带是的,谢谢伙计
猜你喜欢
  • 2014-11-11
  • 2014-09-07
  • 2013-10-08
  • 2014-08-13
  • 1970-01-01
  • 2017-10-28
  • 1970-01-01
  • 2018-05-09
  • 1970-01-01
相关资源
最近更新 更多