0

In android, I open a bitmap from the image picker, and load it into a imageview. If the user selects a big image, the app will crash. I tried try/catch, but it didn't work.

Is there a way to check the file size before loading it into a bitmap?

This is the code:

This is the return function from when I choose an image

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

this is from another file

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));
    }
}

another file

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;
}

This line

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

from the handleResult function, causes a outofmemory error when a user loads a big image.

How can I fix this?

Thanks.

omega
  • 40,311
  • 81
  • 251
  • 474

1 Answers1

0

try code similar to this, you just need to get a File object from the Bitmap you intend to check:

File file = new File(uri); // or new File(filePath);
file.length() // should give you a file size in bytes
Clarkarot
  • 116
  • 1
  • 9
  • The memory needed to load a Bitmap depends on the bitmap's dimensions (i.e. width by height) and is not (necessarily) correlated to the file size. – matiash Jul 03 '14 at 01:33
  • How do you know the width/height threshold so it won't crash? – omega Jul 03 '14 at 02:01
  • If you want the uncompressed bitmap size, you can't really rely on file size alone with my solution then. You could count the bytes read from a bitmap stream until you hit a target threshold you feel is too much and then abort that operation. – Clarkarot Jul 03 '14 at 19:14