【问题标题】:Android: App crashes on the device while uploading images,java.lang.outofMemoryErrorAndroid:上传图片时应用程序在设备上崩溃,java.lang.outofMemoryError
【发布时间】:2013-10-17 14:42:09
【问题描述】:

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

【问题讨论】:

  • 您正在加载的位图可能对于您的测试设备上的可用内存量来说太大了。或者,您可能一次将太多位图加载到图库中。人们经常遇到这种情况,在 Android 上处理位图时,您必须对代码进行一些深思熟虑。以下是 Romain Guy 的演讲,涉及该主题:dl.google.com/io/2009/pres/…
  • @Turnsole 非常感谢它的工作正常

标签: java android bitmap android-image


【解决方案1】:

您应该在 onActivityResult() 方法上解码图像 uri。 调用该方法对位图进行解码。

/**
     * 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

希望得到帮助。

【讨论】:

    【解决方案2】:

    您将在此处找到出现此异常的原因以及如何正确显示位图:http://developer.android.com/training/displaying-bitmaps/index.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多