无法压缩回收的位图错误

时间:2018-06-22 11:58:41

标签: android bitmap

我的应用程序中出现“无法压缩回收的位图错误”。它发生在我的代码中的picture.compress(Bitmap.CompressFormat.PNG, 90, fos);行上:

    private void savePicture(byte[] data, String gameId, String folderName ) {
        File pictureFile = getOutputMediaFile(gameId, folderName);
        if (pictureFile == null){
            Log.error("Error creating media file, check storage permissions.");
            return;
        }

        Bitmap picture = BitmapFactory.decodeByteArray(data, 0, data.length);

        picture = getResizedBitmap(picture, bitmapWidth, bitmapHeight);

        try {
            FileOutputStream fos = new FileOutputStream(pictureFile);

            picture.compress(Bitmap.CompressFormat.PNG, 90, fos);
            fos.close();
            picture.recycle();

            Log.info(">>> CameraActivity: PICTURE SAVED!");

        } catch (FileNotFoundException e) {
            Log.error(LibUtil.getStackTrace(e));
        } catch (IOException e) {
            Log.error(LibUtil.getStackTrace(e));
        }
    }

    public Bitmap getResizedBitmap(Bitmap bmp, int newWidth, int newHeight) {
        int width = bmp.getWidth();
        int height = bmp.getHeight();
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // CREATE A MATRIX FOR THE MANIPULATION
        Matrix matrix = new Matrix();
        // RESIZE THE BIT MAP
        matrix.postScale(scaleWidth, scaleHeight);

        // "RECREATE" THE NEW BITMAP
        Bitmap resizedBitmap = Bitmap.createBitmap(
                bmp, 0, 0, width, height, matrix, false);
        bmp.recycle();
        return resizedBitmap;
    }

我发现特别的是,当我注释bmp.recycle();行时,错误消失了。 resizedBitmapbmp似乎(IMHO)引用了同一位图。但是我不知道这是否是正确的选择,是否存在内存泄漏或我的应用程序中没有其他内容。

顺便说一句,此代码不会在任何ImageView上显示位图,而只是在场景后定期从相机拍摄一张照片并将其保存。

谢谢。

3 个答案:

答案 0 :(得分:4)

createBitmap的版本并不总是返回新的Bitmap。在您的情况下,如果resizedBitmap等于bmp,则您都在回收这两个值(相同的引用)。在您的getResizedBitmap中添加

 if (resizedBitamp != bmp) {
    bmp.recycle();
 }
  

但是我不知道这是否是正确的选择,没有   内存泄漏或我的应用中的任何内容。

与内存泄漏无关。

答案 1 :(得分:0)

为什么要循环使用两次位图?您无法对回收的产品进行操作。我的意思是它不能被压缩,不能再次循环使用。删除行bmp.recycle();是没有用的,因为您稍后在try条件下将其循环使用,就像我在一开始所说的那样,您不能循环使用已经循环使用的位图。 / p>

答案 2 :(得分:0)

从您的bmp.recycle();方法中删除getResizedBitmap 因为您要打两次电话,所以请除掉recycle()或将其移至要使用位图完成的所有操作之后

相关问题