Android无法压缩回收的Bitmap

时间:2016-09-14 15:48:48

标签: android url bitmap

我从网址获取图片,我想压缩它并将其保存在外部存储设备中。我收到了错误

  

java.lang.IllegalStateException:           无法压缩回收的位图           在android.graphics.Bitmap.checkRecycled(Bitmap.java:400)           在android.graphics.Bitmap.compress(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 个答案:

答案 0 :(得分:1)

错误消息是"无法压缩回收的位图"。如果你在mIcon11.compress(Bitmap.CompressFormat.JPEG, 40, bytes);行之前看三行,你会看到:

mIcon11.recycle();

所以,要么摆脱recycle(),要么在之后将其移动到,你已经完成了所有你打算用Bitmap指向到mIcon11