[心缘地方]同学录
首页 | 功能说明 | 站长通知 | 最近更新 | 编码查看转换 | 代码下载 | 常见问题及讨论 | 《深入解析ASP核心技术》 | 王小鸭自动发工资条VBA版
登录系统:用户名: 密码: 如果要讨论问题,请先注册。

[备忘]android图片,can't call getPixels() on a recycled bitmap

上一篇:[备忘]postgresql数据库删除重复数据的一条
下一篇:[备忘]postgresql,pg_dump导出为insert语句

添加日期:2023/7/7 11:08:18 快速返回   返回列表 阅读247次


        //转Bitmap
        Bitmap image = BitmapFactory.decodeByteArray(imageData, 0, imageData.length);

        //XML里宽度是字符个数
        int imageWith = Integer.valueOf(xmlWidth) * printer.getFontWidth();

        //缩放图片
        image = ToolsUtil.getScaledImage(image, imageWith, 200);

        //外部图片,需要转黑白图(不要抖动,一般是logo图)
        if (extSource.equals("1")) {
            image = ToolsUtil.convertToBlackWhite(image);
        }


大概代码如上,字节数据转成Bitmap,然后缩放一下,然后转黑白图,
错误是黑白图这里报出来的,那么说明image被回收了。

缩放代码如下:


   /**
     * 图片缩放.
     *
     * @param srcImg 原图片
     * @param width  宽
     * @param height 高
     * @return 缩放后图片
     */
    public static Bitmap getScaledImage(Bitmap srcImg, int width, int height) {
        int srcWidth = srcImg.getWidth();
        int srcHeight = srcImg.getHeight();
        double rate = 1.0;
        int newWidth = 1;
        int newHeight = 1;

        //宽度太大,就缩小宽度(也可以放大图片)
        rate = (0.0 + width) / srcWidth;
        newWidth = width; //宽度定值
        newHeight = Double.valueOf(srcHeight * rate).intValue(); //高度比例缩小

        Bitmap newImg = Bitmap.createScaledBitmap(srcImg, newWidth, newHeight, true);
        srcImg.recycle();
        return newImg;
    }


看着没啥问题啊,百思不得其解~~

后来搜了下,貌似createScaledBitmap可能返回原图片,找到api说明:
https://developer.android.com/reference/android/graphics/Bitmap#createScaledBitmap(android.graphics.Bitmap,%20int,%20int,%20boolean)


public static Bitmap createScaledBitmap (Bitmap src, 
                int dstWidth, 
                int dstHeight, 
                boolean filter)
Creates a new bitmap, scaled from an existing bitmap, when possible. If the specified width and height are the same as the current width and height of the source bitmap, the source bitmap is returned and no new bitmap is created.


果然如此,如果高度宽度没变,直接返回原图片,没有新做一个。

故代码修改一下:
if (newImg != srcImg) {
    srcImg.recycle();
}
即可
 

评论 COMMENTS
没有评论 No Comments.

添加评论 Add new comment.
昵称 Name:
评论内容 Comment:
验证码(不区分大小写)
Validation Code:
(not case sensitive)
看不清?点这里换一张!(Change it here!)
 
评论由管理员查看后才能显示。the comment will be showed after it is checked by admin.
CopyRight © 心缘地方 2005-2999. All Rights Reserved