//转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(); } 即可
|