3

I am using a bitmap. It throws out of memory error (2 out of 5 times). How can it be avoided.

Following is my code:

  bitmap = android.provider.MediaStore.Images.Media.getBitmap(cr, imageUri);
  photo_new= rotateImage(bitmap, 90);
  ByteArrayOutputStream stream = new ByteArrayOutputStream();

  photo_new.compress(Bitmap.CompressFormat.JPEG, 100, stream);
  byte[] byteArray = stream.toByteArray();

  Intent i = new Intent(getApplicationContext(),new_class.class);
  i.putExtra("image", byteArray);

  startActivity(i);
  byteArray=null;
Prashant
  • 35
  • 8
user1619306
  • 169
  • 1
  • 5
  • 12

3 Answers3

6

You are getting OutOfMemoryError because you haven't recycle those bitmaps you used

try to recycle those bitmaps after you used them

bitmap = android.provider.MediaStore.Images.Media.getBitmap(cr, imageUri);
  photo_new= rotateImage(bitmap, 90);
  ByteArrayOutputStream stream = new ByteArrayOutputStream();

  photo_new.compress(Bitmap.CompressFormat.JPEG, 100, stream);
  byte[] byteArray = stream.toByteArray();
  bitmap.recycle();
  Intent i = new Intent(getApplicationContext(),new_class.class);
  i.putExtra("image", byteArray);

  startActivity(i);
  byteArray=null;
Kaushik
  • 6,150
  • 5
  • 39
  • 54
  • Am using the above code without any modification, but unfortunately first line itself giving me OutOffMemory error. MediaStore.Images.Media.getBitmap(cr, imageUri); //in this line it is crashed – Anbarasu Chinna Jan 21 '19 at 10:25
  • https://stackoverflow.com/questions/11381113/mediastore-images-media-getbitmap-and-out-of-memory-error @AnbarasuChinna – Kaushik Jan 21 '19 at 11:30
3
  byte[] byteArray = stream.toByteArray();

in that line your ram is getting filled by whole Bitmap. Change bitmap quality from 100 to 50-60 as below

 photo_new.compress(Bitmap.CompressFormat.JPEG, 50, stream);

or

 photo_new.compress(Bitmap.CompressFormat.JPEG, 60, stream);

try both and see the results.

Sercan Ozdemir
  • 4,641
  • 3
  • 34
  • 64
0

wrong

1). Bitmap quality is high.

2). you are not using try catch.

Suggestions

1). reduce the quality of bitmap to 45-50.

2). use try catch block to prevent your app from crash.

Solution // sender activity

try{
     Intent _intent = new Intent(this, newscreen.class);
     Bitmap _bitmap; // your bitmap
     ByteArrayOutputStream _bs = new ByteArrayOutputStream();
     _bitmap.compress(Bitmap.CompressFormat.PNG, 50, _bs);
     i.putExtra("byteArray", _bs.toByteArray());
     startActivity(i);
}catch(Exception e){
}

receiver activity

try{
     if(getIntent().hasExtra("byteArray")) {

     ImageView _imv= new ImageView(this);
     Bitmap _bitmap = BitmapFactory.decodeByteArray(getIntent().getByteArrayExtra("byteArray"),0,getIntent().getByteArrayExtra("byteArray").length);        
    _imv.setImageBitmap(_bitmap);
 }
}catch(Exception e){
 }
Kaushik
  • 6,150
  • 5
  • 39
  • 54
Pankaj Arora
  • 10,224
  • 2
  • 37
  • 59