Vajira Lasantha Vajira Lasantha - 1 year ago 213
Android Question

Android BitmapFactory decodeResource Out of Memory Exception [FIXED]

I'm new to android and developing an app that saves large images from drawable folder to phone storage. These files have resolution of 2560x2560 and I want to save these files without loosing image quality.

I use following method to save images and it gives me Out of Memory Exception. I have seen many answers how to load a large bitmap efficiently. But I cant really find an answer for this problem.

In my code, I use

Bitmap bitmap = BitmapFactory.decodeResource(getResources(), imageId);
File file = new File(root.getAbsolutePath() + "/Pictures/" + getResources().getString(R.string.app_name) + "/" + timeStamp + ".jpg");
FileOutputStream oStream = new FileOutputStream(file);
bitmap.compress(CompressFormat.JPEG, 100, oStream);

Is there anything wrong with my code? This works without any exception for smaller images.

If I use
, this does not throw any exception. But I know it is not a good practice to use

Is there any efficient way to save large images from drawable folder without an exception?

Thank you in advance.

Answer Source

If you just want to copy the image file, you shouldn't decode it into a bitmap in the first place.

You can copy a raw resource file with this for example:

InputStream in = getResources().openRawResource(imageId);
String path = root.getAbsolutePath() + "/Pictures/" + getResources().getString(R.string.app_name) + "/" + timeStamp + ".jpg";
FileOutputStream out = new FileOutputStream(path);
try {
    byte[] b = new byte[4096];
    int len = 0;
    while ((len = > 0) {
        out.write(b, 0, len);
finally {

Note that you have to store your image in the res/raw/ directory instead of res/drawable/.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download