java图像裁剪
我知道BufferedImage.getSubimage
然而,它无法处理小于抛出exception的裁剪大小的裁剪图像:
java.awt.image.RasterFormatException: (y + height) is outside raster
我希望能够将PNG / JPG / GIF裁剪为特定尺寸,但是如果图像小于裁剪区域中心本身在白色背景上。 是否有电话要这样做? 或者我是否需要手动创建图像以使图像居中,如果是这样,我将如何处理?
谢谢
您无法裁剪更大,更小的图像。 所以,你从目标维度开始,比方说100×100。 而你的BufferedImage
( bi
),比方说150×50。
创建一个目标矩形:
Rectangle goal = new Rectangle(100, 100);
然后将其与图像的尺寸相交:
Rectangle clip = goal.intersection(new Rectangle(bi.getWidth(), bi.getHeight());
现在,clip对应于适合您目标的bi
部分。 在这种情况下100 x50。
现在使用clip
的值获取subImage
。
BufferedImage clippedImg = bi.subImage(clip,1, clip.y, clip.width, clip.height);
创建一个新的BufferedImage
( bi2
), goal
大小:
BufferedImage bi2 = new BufferedImage(goal.width, goal.height);
用白色填充(或者你选择的任何bg颜色):
Graphics2D big2 = bi2.getGraphics(); big2.setColor(Color.white); big2.fillRect(0, 0, goal.width, goal.height);
并将剪裁的图像绘制到其上。
int x = goal.width - (clip.width / 2); int y = goal.height - (clip.height / 2); big2.drawImage(x, y, clippedImg, null);