java图像裁剪

Jam*_*ore 4 java image-manipulation

我知道BufferedImage.getSubimage但是,它无法处理小于裁剪异常的裁剪图像的裁剪图像:

java.awt.image.RasterFormatException: (y + height) is outside raster
Run Code Online (Sandbox Code Playgroud)

我希望能够将PNG/JPG/GIF裁剪为特定尺寸,但是如果图像小于裁剪区域中心本身在白色背景上.是否有电话要这样做?或者我是否需要手动创建图像以使图像居中,如果是这样,我将如何处理?

谢谢

Dev*_*ler 9

您无法裁剪更大,更小的图像.所以,你从目标维度开始,比方说100x100.而你的BufferedImage(bi),比方说150x50.

创建一个目标矩形:

Rectangle goal = new Rectangle(100, 100);
Run Code Online (Sandbox Code Playgroud)

然后将其与图像的尺寸相交:

Rectangle clip = goal.intersection(new Rectangle(bi.getWidth(), bi.getHeight());
Run Code Online (Sandbox Code Playgroud)

现在,clip对应于bi适合您目标的部分.在这种情况下100 x50.

现在得到subImage使用的值clip.

BufferedImage clippedImg = bi.subImage(clip,1, clip.y, clip.width, clip.height);
Run Code Online (Sandbox Code Playgroud)

创建一个new BufferedImage(bi2),大小为goal:

BufferedImage bi2 = new BufferedImage(goal.width, goal.height);
Run Code Online (Sandbox Code Playgroud)

用白色填充(或者你选择的任何bg颜色):

Graphics2D big2 = bi2.getGraphics();
big2.setColor(Color.white);
big2.fillRect(0, 0, goal.width, goal.height);
Run Code Online (Sandbox Code Playgroud)

并将剪裁的图像绘制到其上.

int x = goal.width - (clip.width / 2);
int y = goal.height - (clip.height / 2);
big2.drawImage(x, y, clippedImg, null);
Run Code Online (Sandbox Code Playgroud)