2016-09-14 50 views
-2

我從URL中獲取圖像,我想壓縮並將其保存在外部存儲設備中。我得到這個錯誤Android無法壓縮回收的位圖

java.lang.IllegalStateException: 不能android.graphics.Bitmap在android.graphics.Bitmap.checkRecycled(Bitmap.java:400) 壓縮回收位 。壓縮(Bitmap.java:1307)

在這條線

mIcon11.compress(Bitmap.CompressFormat.JPEG, 40, bytes); 

String foto = UT_drive_dropbox.AM.getfoto(); 
Bitmap mIcon11 = null; 
    try { 
     InputStream in = new java.net.URL(foto).openStream(); 
     mIcon11 = BitmapFactory.decodeStream(in); 
    } catch (Exception e) { 
     Log.e("Error", e.getMessage()); 
     e.printStackTrace(); 
    } 
final Bitmap output = Bitmap.createBitmap(mIcon11.getWidth(), 
      mIcon11.getHeight(), Bitmap.Config.ARGB_8888); 
    final Canvas canvas = new Canvas(output); 

    final int color = Color.RED; 
    final Paint paint = new Paint(); 
    final Rect rect = new Rect(0, 0, mIcon11.getWidth(), mIcon11.getHeight()); 
    final RectF rectF = new RectF(rect); 

    paint.setAntiAlias(true); 
    canvas.drawARGB(0, 0, 0, 0); 
    paint.setColor(color); 
    canvas.drawOval(rectF, paint); 

    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); 
    canvas.drawBitmap(mIcon11, rect, rect, paint); 

    mIcon11.recycle(); 


    String fileName = "avatar.jpg"; 
    ByteArrayOutputStream bytes = new ByteArrayOutputStream(); 
    mIcon11.compress(Bitmap.CompressFormat.JPEG, 40, bytes); 

    File sd = new File(Environment.getExternalStorageDirectory(), getString(R.string.app_name) + File.separator + fileName); 

    FileOutputStream fileOutputStream = null; 
    try { 
     sd.createNewFile(); 
     fileOutputStream = new FileOutputStream(sd); 
     fileOutputStream.write(bytes.toByteArray()); 

    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } finally { 
     if (fileOutputStream != null) { 
      try { 
       fileOutputStream.close(); 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
     } 
    } 

回答

1

錯誤消息是「無法壓縮回收的位圖」。如果您mIcon11.compress(Bitmap.CompressFormat.JPEG, 40, bytes);線前三條線路,你會看到:

mIcon11.recycle(); 

所以,要麼擺脫recycle()或將其移動到後,你做了一切,你打算與Bitmap針對性的做到mIcon11

+2

只要添加到這個上面,只有在完成對象時才應該調用'recycle()'。在對象中間調用它是100%錯誤的,就像喝了一杯飲料,把它扔到回收箱中間,然後想知道爲什麼你不能再喝這種飲料。 – CodyEngel