Android:在上传图片时,应用程序在设备上崩溃,java.lang.outofMemoryError

时间:2013-10-17 14:42:09

标签: java android bitmap android-image

在我的Android应用程序中,我必须允许用户单击按钮以打开图库并选择图像。然后需要将特定的选定图像加载到我的布局(UI)中的图像视图中。我有一些代码,但它来自java.lang.outofmemory.Please任何人都可以帮助我?

2 个答案:

答案 0 :(得分:3)

您应该在onActivityResult()方法上解码图像uri。 将此方法称为decodeBitmap。

/**
     * This is very useful to overcome Memory waring issue while selecting image
     * from Gallery
     * 
     * @param selectedImage
     * @param context
     * @return Bitmap
     * @throws FileNotFoundException
     */
    public static Bitmap decodeBitmap(Uri selectedImage, Context context)
            throws FileNotFoundException {
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(context.getContentResolver()
                .openInputStream(selectedImage), null, o);

        final int REQUIRED_SIZE = 100;

        int width_tmp = o.outWidth, height_tmp = o.outHeight;
        int scale = 1;
        while (true) {
            if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE) {
                break;
            }
            width_tmp /= 2;
            height_tmp /= 2;
            scale *= 2;
        }

        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        return BitmapFactory.decodeStream(context.getContentResolver()
                .openInputStream(selectedImage), null, o2);
    }

有关详细信息,请参阅主题有效显示位图

http://developer.android.com/training/displaying-bitmaps/index.html

希望得到这个帮助。

答案 1 :(得分:0)

在这里,您将了解为什么会出现此异常以及如何正确显示位图:http://developer.android.com/training/displaying-bitmaps/index.html