我知道BufferedImage.getSubimage
然而,它无法处理小于裁剪异常的裁剪尺寸的裁剪图像:
java.awt.image.RasterFormatException: (y + height) is outside raster
我希望能够将PNG / JPG / GIF裁剪为特定尺寸,但是如果图像小于裁剪区域中心本身在白色背景上。是否有电话要这样做?或者我是否需要手动创建图像以使图像居中(如果是这样),我将如何解决这个问题?
由于
答案 0 :(得分:9)
您无法裁剪更大,更小的图像。所以,你从目标维度开始,比方说100x100。而你的BufferedImage
(bi
),比方说150x50。
创建目标矩形:
Rectangle goal = new Rectangle(100, 100);
然后将其与图像的尺寸相交:
Rectangle clip = goal.intersection(new Rectangle(bi.getWidth(), bi.getHeight());
现在,剪辑对应于适合您目标的bi
部分。在这种情况下100 x50。
现在使用subImage
的值获取clip
。
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);