该异常一般发生在使用Bitmap进行图像处理时,特别是在处理较大图像时。如果在网络上传输大型图像时也会出现这种情况。为解决这个问题,可以采取以下措施:
1.使用ByteArray来传输Bitmap,并将其写入文件,必要时可以一部分一部分地进行读取和写入,这样可以节省内存,避免OutOfMemoryException异常。例如:
Bitmap bmp = BitmapFactory.decodeFile("yourfile.jpg"); ByteArrayOutputStream stream = new ByteArrayOutputStream(); bmp.compress(Bitmap.CompressFormat.PNG, 100, stream); byte[] byteArray = stream.toByteArray(); // 通过网络传输byteArray,并在另一端进行操作 ...
2.尽可能使用ARGB_8888格式的Bitmap,并避免使用ALPHA_8和RGB_565格式。ARGB_8888需要更多的内存,但是处理图像时更加灵活和高效。例如:
options.inPreferredConfig = Bitmap.Config.ARGB_8888; Bitmap bmp = BitmapFactory.decodeFile("yourfile.jpg", options);
3.及时回收不再使用的Bitmap,释放内存。例如:
if (bmp != null && !bmp.isRecycled()) { bmp.recycle(); bmp = null; }
4.如果需要同时处理多张图片,可以采用分批处理的方式,将大任务拆分为多个小任务,避免一次性加载过多的图片并耗尽内存。
通过以上措施,可以有效避免Bitmap处理过程中的OutOfMemoryException异常。