osemec
osemec

Reputation: 259

Android camera Bitmap memory leak

I write a simple code to take a picture and then display it to the screen using ImageView. However, there is some memory leak, which I don't find. (The memory goes from 7 MB to 39 MB after taking a picture)

public class MainActivity extends Activity {

    public String gl;
    ImageView viewImage;
    Button b;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        b = (Button) findViewById(R.id.myButton);
        viewImage = (ImageView) findViewById(R.id.myImageView);
    }

    public void launchCamera(View view) {//Button onClick method
        Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
        gl = f.getAbsolutePath();
        i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
        startActivityForResult(i, 1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == RESULT_OK) {
            Bitmap bitmap;
            BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
            bitmap = BitmapFactory.decodeFile(gl, bitmapOptions);
            viewImage.setImageBitmap(bitmap);
        }
    }
}

Upvotes: 1

Views: 1097

Answers (2)

Stephane Mathis
Stephane Mathis

Reputation: 6622

Picture can be huge in memory, each pixel is taking 32 bits in memory.

You should load a reduced version of the image and not the full size. I'm even surprise you don't get an error for loading more than 2048*2048 pixel image.

Upvotes: 1

Rajesh Jadav
Rajesh Jadav

Reputation: 12861

Here is link:

https://stackoverflow.com/a/32245332/3702862

In which i have given efficient way to take a picture from Camera and then display it in ImageView.

I hope it helps you.

Upvotes: 1

Related Questions