【问题标题】:Out of memory error in android bitmapandroid位图中的内存不足错误
【发布时间】:2014-06-13 11:13:00
【问题描述】:

我正在使用位图。它抛出内存不足错误(5 次中有 2 次)。 怎么可能避免。

以下是我的代码

  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;

【问题讨论】:

  • 它适用于不同的图像?有什么区别。什么时候会引发内存错误?
  • 这些位图的大小是多少?
  • 它抛出错误:bitmap = android.provider.MediaStore.Images.Media.getBitmap(cr, imageUri);

标签: java android bitmap out-of-memory


【解决方案1】:

你得到OutOfMemoryError,因为你没有recycle 你用的那些bitmaps

在你使用它们之后尝试recycle那些bitmaps

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;

【讨论】:

  • 我使用上面的代码没有任何修改,但不幸的是第一行本身给了我 OutOffMemory 错误。 MediaStore.Images.Media.getBitmap(cr, imageUri); //在这一行中它崩溃了
【解决方案2】:
  byte[] byteArray = stream.toByteArray();

在那一行中,你的 ram 被整个 Bitmap 填满。将位图质量从 100 更改为 50-60,如下所示

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

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

两者都试一下,看看结果。

【讨论】:

    【解决方案3】:

    错误

    1)。位图质量很高。

    2)。你没有使用 try catch。

    建议

    1)。将位图质量降低到 45-50。

    2)。使用 try catch 块来防止您的应用崩溃。

    解决方案 // 发送者活动

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

    接收者活动

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

    【讨论】:

      猜你喜欢
      • 2013-01-17
      • 1970-01-01
      • 2012-07-21
      • 1970-01-01
      • 2011-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多