处理图像时出现OutOfMemoryexception

可能重复:
OutOfMemoryError:位图大小超过VM预算: – Android

我正在编写一个程序,使用来自图库的图像,然后在活动中显示它们(一个图像pr。活动)。 然而,我一直在连续三天碰到这个错误而没有取消它的任何进展:

07-25 11:43:36.197: ERROR/AndroidRuntime(346): java.lang.OutOfMemoryError: bitmap size exceeds VM budget 

我的代码流程如下:

当用户按下按钮时,会触发通向图库的意图:

  Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT); galleryIntent.setType("image/*"); startActivityForResult(galleryIntent, 0); 

用户选择图像后,图像将以图像视图显示:

     

在onActivityResult方法中我有:

 @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if(resultCode == RESULT_OK) { switch(requestCode) { case 0: // Gallery String realPath = getRealPathFromURI(data.getData()); File imgFile = new File(realPath); Bitmap myBitmap; try { myBitmap = decodeFile(imgFile); Bitmap rotatedBitmap = resolveOrientation(myBitmap); img.setImageBitmap(rotatedBitmap); OPTIONS_TYPE = 1; } catch (IOException e) { e.printStackTrace(); } insertImageInDB(realPath); break; case 1: // Camera 

decodeFile方法来自此处 ,resolveOrientation方法只是将位图包装成矩阵并顺时针旋转90度。

我真的希望有人可以帮我解决这个问题。

这是因为您的位图大小很大,因此请手动或通过编程方式缩小图像大小

 BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 8; Bitmap preview_bitmap = BitmapFactory.decodeFile(mPathName, options); 

您的GC无法运行。 尝试逐个获取位图

 BitmapFactory.Options buffer = new BitmapFactory.Options(); buffer.inSampleSize = 4; Bitmap bmp = BitmapFactory.decodeFile(path, buffer); 

Stackoverflow中有很多关于位图大小超过VM预算的问题所以首先搜索一下你的问题,当你找不到任何解决方案时,请在这里提问

问题是因为您的位图大小太大而不是VM可以处理的大小。 例如,从您的代码中我可以看到您正在尝试将Image粘贴到使用Camera捕获的imageView中。 所以通常相机图像的尺寸太大会明显地增加这个错误。 正如其他人所建议的那样,您必须通过采样或将图像转换为更小的分辨率来压缩图像。 例如,如果您的imageView的宽度和高度为100×100,则可以创建缩放的位图,以便精确填充imageView。 你可以这样做,

  Bitmap newImage = Bitmap.createScaledBitmap(bm, 350, 300,true); 

或者您可以使用用户hotveryspicy建议的方法对其进行抽样。