How to avoid OutOfMemory Exception in android- Second Method?

By | July 24, 2011

In the previous tutorial I showed you one method to avoid OutOfMemory Exception in android.
And In this tutorial I will show you another method.
The reduceImageSize function in this code reduces the image to the desired size you want.
Create a fresh project and copy this code into it.
How to put images inside the emulator is shown in this example.

This example shows how to get an image from inside the gallery.
And this example show how to copy images from gallery to another location in SDCARD.

Give your requred size in the varisble REQUIRED_SIZE to change according to your wish.

package pack.coderzheaven;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class GetImageActivity extends Activity {

	private static final int SELECT_PICTURE = 1;

	private String selectedImagePath;
	private ImageView img;

	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.main);

	    img = (ImageView)findViewById(R.id.ImageView01);

	    ((Button) findViewById(R.id.Button01))
	            .setOnClickListener(new OnClickListener() {
	                public void onClick(View arg0) {
	                    Intent intent = new Intent();
	                    intent.setType("image/*");
	                    intent.setAction(Intent.ACTION_GET_CONTENT);
	                    startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE);
	                }
	            });
	}

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
	    if (resultCode == RESULT_OK) {
	        if (requestCode == SELECT_PICTURE) {
	            Uri selectedImageUri = data.getData();
	            selectedImagePath = getPath(selectedImageUri);
	            System.out.println("Image Path : " + selectedImagePath);
	            Bitmap bm = reduceImageSize(selectedImagePath);
	            if(bm != null)
	            	img.setImageBitmap(bm);
	        }
	    }
	}

	public String getPath(Uri uri) {
	    String[] projection = { MediaStore.Images.Media.DATA };
	    Cursor cursor = managedQuery(uri, projection, null, null, null);
	    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
	    cursor.moveToFirst();
	    return cursor.getString(column_index);
	}

	public Bitmap reduceImageSize(String mSelectedImagePath){

	    	Bitmap m = null;
		    try {
	      	  File f = new File(mSelectedImagePath);

	      	//Decode image size
	          BitmapFactory.Options o = new BitmapFactory.Options();
	          o.inJustDecodeBounds = true;
	          BitmapFactory.decodeStream(new FileInputStream(f),null,o);

	          //The new size we want to scale to
	          final int REQUIRED_SIZE=150;

	          //Find the correct scale value. It should be the power of 2.
	          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;
	          }

	          //Decode with inSampleSize
	          BitmapFactory.Options o2 = new BitmapFactory.Options();
	          o2.inSampleSize=scale;
	          m = BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
	      } catch (FileNotFoundException e) {
	    	  Toast.makeText(getApplicationContext(), "Image File not found in your phone. Please select another image.", Toast.LENGTH_LONG).show();
	      }
	      return  m;
	}
}


Click the +1 button on the top to share it with your friends and please leave your valuable comments also.

2 thoughts on “How to avoid OutOfMemory Exception in android- Second Method?

  1. Travis

    DUDE!!! I love you. I was trying to figure this out for the past two hours, and was on the verge of blowing my brains out haha. I hope you have a great day/rest of the week/ rest of your LIFE. Thank you soo much man

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *