无法压缩回收的位图?

时间:2018-09-24 11:03:54

标签: android bitmap

我正在尝试将位图压缩为JPEG格式,但是由于某些原因,我收到此错误Can't compress a recycled bitmap

我不知道它来自哪里。

代码

    public class BackgroundImageResize extends AsyncTask<Uri, Integer, byte[]> {

    Bitmap mBitmap;
    public BackgroundImageResize(Bitmap bm) {
        if(bm != null){
            mBitmap = bm;
        }
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        //  showDialog();
        Log.d(TAG,"Compressing image");
    }

    @Override
    protected byte[] doInBackground(Uri... params ) {
        Log.d(TAG, "doInBackground: started.");

        if(mBitmap == null){

            try {
                mBitmap = MediaStore.Images.Media.getBitmap(MyAccount.this.getContentResolver(), params[0]);
                Log.d(TAG, "doInBackground: bitmap size: megabytes: " + mBitmap.getByteCount()/MB + " MB");
            } catch (IOException e) {
                Log.e(TAG, "doInBackground: IOException: ", e.getCause());
            }
        }

        byte[] bytes = null;
        for (int i = 1; i < 11; i++){
            if(i == 10){
                Toast.makeText(MyAccount.this, "That image is too large.", Toast.LENGTH_SHORT).show();
                break;
            }
            bytes = getBytesFromBitmap(mBitmap,100/i);
            Log.d(TAG, "doInBackground: megabytes: (" + (11-i) + "0%) "  + bytes.length/MB + " MB");
            if(bytes.length/MB  < MB_THRESHHOLD){
                return bytes;
            }
        }
        return bytes;
    }


    @Override
    protected void onPostExecute(byte[] bytes) {
        super.onPostExecute(bytes);
        // hideDialog();
        mBytes = bytes;
        //execute the upload
        executeUploadTask();
    }
}

已编辑

// convert from bitmap to byte array
 public static byte[] getBytesFromBitmap(Bitmap bitmap, int quality) {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.copy(bitmap.getConfig(),true).compress(Bitmap.CompressFormat.JPEG, quality, stream);
    return stream.toByteArray();
}

我在bitmap.compress(Bitmap.CompressFormat.JPEG, quality, stream);上遇到错误 我不明白位图是如何回收的。我从未使用过回收位图或使用我以前使用过的位图的任何方法。 所以这让我感到困惑。

有什么想法要解决吗?

0 个答案:

没有答案