【问题标题】:How to avoid out of memory errors in android when loading big bitmaps?加载大位图时如何避免android中的内存不足错误?
【发布时间】:2014-07-03 00:20:04
【问题描述】:

在 android 中,我从图像选择器中打开一个位图,并将其加载到 imageview 中。如果用户选择大图像,应用程序将崩溃。我尝试了 try/catch,但没有成功。

有没有办法在将文件加载到位图之前检查文件大小?

这是代码:

这是我选择图片时的返回函数

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
        ImageUploadHandler.handleResult(this, data);
    }
}

这是来自另一个文件

public void handleResult(Context context, Intent data) {
    Bitmap bitmap = null;

    try {
        bitmap = MyImage.GetBitmapFromPath(context, data.getData());         
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        bitmap.compress(CompressFormat.PNG, 100, out);

        int size = out.size();
        isReady = size <= IMAGE_THRESHOLD;
    } catch (Exception e) {
        isReady = false;
        Log.d("Image Error", e.getMessage());
    }

    if (isReady) {
        DialogImageView.setImageBitmap(bitmap);
        DialogStatus.setText(context.getString(R.string.image_ok));
    } else {
        DialogImageView.setImageDrawable(null);
        DialogStatus.setText(context.getString(R.string.too_big_image));
    }
}

另一个文件

public static Bitmap GetBitmapFromPath(Context context, Uri uri) {
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    String filePath = cursor.getString(column_index);
    cursor.close();
    Bitmap bitmap = BitmapFactory.decodeFile(filePath);
    return bitmap;
}

这一行

bitmap = MyImage.GetBitmapFromPath(context, data.getData());  

来自 handleResult 函数,当用户加载大图像时导致内存不足错误。

我该如何解决这个问题?

谢谢。

【问题讨论】:

标签: android bitmap out-of-memory


【解决方案1】:

试试类似这样的代码,你只需要从你要检查的Bitmap中获取一个File对象:

File file = new File(uri); // or new File(filePath);
file.length() // should give you a file size in bytes

【讨论】:

  • 加载位图所需的内存取决于位图的尺寸(即宽度与高度),并且与文件大小没有(必然)相关。
  • 你怎么知道宽度/高度阈值所以它不会崩溃?
  • 如果你想要未压缩的位图大小,那么我的解决方案不能只依赖文件大小。您可以计算从位图流中读取的字节数,直到达到您认为过多的目标阈值,然后中止该操作。
猜你喜欢
  • 2014-02-19
  • 1970-01-01
  • 1970-01-01
  • 2012-12-23
  • 1970-01-01
  • 1970-01-01
  • 2011-09-01
  • 2012-09-21
  • 2012-12-30
相关资源
最近更新 更多