处理图像时出现OutOfMemory异常

5
我正在编写一个程序,该程序使用来自画廊的图像,然后在一个活动中显示它们(每个活动一个图像)。但是,我连续三天都遇到了这个错误,一直无法解决它,这是错误信息:OutOfMemoryError: bitmap size exceeds VM budget :- Android
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);

用户选择了一张图片后,该图片会在一个ImageView中呈现:

  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent"
     android:orientation="vertical">

<ImageView
    android:background="#ffffffff"
    android:id="@+id/image"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_gravity="center"
    android:maxWidth="250dip"
    android:maxHeight="250dip"
    android:adjustViewBounds="true"/>

 </LinearLayout>

在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度。希望有人能帮我解决这个问题。


请参考以下链接:https://dev59.com/E3A85IYBdhLWcg3wHv7B 或 http://stackoverflow.com/questions/6131927/bitmap-size-exceeds-vm-budget-in-android。 - THelper
@THelper:你知道怎么解决这个问题吗?根据你提供的两个链接,我已经实施了“解决方案”,但是没有帮助。 - Arcadia
4个回答

2

这是因为您的位图大小较大,所以需要手动或编程方式缩小图像大小。

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

1

在Stackoverflow上有很多关于位图大小超出VM预算的问题,因此首先请搜索您的问题,如果找不到任何解决方案,请在这里提问。


1

你的垃圾回收器没有运行。尝试分段获取位图。

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

1
问题是因为您的位图大小超过了虚拟机可以处理的范围。例如,从您的代码中可以看出,您正在尝试将使用相机捕获的图像粘贴到imageView中。因此,相机图像的大小通常会很大,这显然会引发此错误。 因此,正如其他人建议的那样,您必须通过对其进行采样或将图像转换为较小的分辨率来压缩图像。 例如,如果您的imageView宽度和高度都是100x100,则可以创建一个缩放的位图,以使您的imageView被填充。您可以这样做:
    Bitmap newImage = Bitmap.createScaledBitmap(bm, 350, 300,true);

或者你可以按照用户hotveryspicy建议的方法进行抽样。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接