android - 无法压缩回收的位图错误

标签 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 引用了相同的位图。但我不知道这样做是否正确,而且我的应用程序中没有内存泄漏或其他任何问题。

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

提前致谢。

最佳答案

createBitmap 的版本并不总是返回一个新的位图。在您的情况下,如果 resizedBitmap 等于 bmp,则您正在回收两者(相同的引用)。在你的 getResizedBitmap 添加

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

But I don't know whether it's the right thing to do and there's no memory leak or whatever in my app.

与内存泄漏无关。

关于android - 无法压缩回收的位图错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50987447/

相关文章:

c# - 保存位图时内存泄漏?

android 使用 nfc 解锁屏幕

java - 改造响应主体接收到具有空字段的一半对象

android - 从使用自定义程序对话框的异步任务更新 TextView

java - 当也有 recyclerview 时,数据绑定(bind)无法在按钮上正常工作

c++ - 无法删除 GDI+ 图像

android - 如何在不改变其他元素可视化的情况下添加 ScrollView?

android - 使用缓存提高带有图像的 Android ListView 中的滚动性能

android - 在发送到服务器之前调整图像大小

c++ - 如何在一个类中存储多个位图?