我正在尝试裁剪 500x500 的图像,使其只有 300x300 的矩形位于中心,如下所示:
Original Image
+-------------------+ +-------------------+
| 500 x 500 | | Crop Area |
| | | +-----------+ |
| | | | 300 x 300 | |
| | | | | |
| | | | | |
| | | +-----------+ |
| | | |
+-------------------+ +-------------------+
我看到Graphics.drawImage()
with 8 int
parameters说它将绘制图像的一个区域,这似乎适合仅绘制图像的裁剪区域,但是当我尝试 image.getGraphics().drawImage(image, 0, 0, 500, 500, 100 , 100, 400, 400, null);
它没有正确裁剪图像。
我应该为 drawImage
提供哪些参数来裁剪图像?
最佳答案
前四个 int 参数表示要绘制的图像(目标图像)的矩形部分,后四个表示要绘制的图像(源图像)的矩形部分。如果这些矩形的大小不同,源图像将重新缩放(增大或缩小)以适合目标图像。您使用 drawImage(image, 0, 0, 500, 500, 100, 100, 400, 400, null)
的尝试不太有效,因为在获得图像的正确区域后,您会增长它适合整个图像。因为您想要裁剪图像(更改其尺寸),所以您必须创建一个适合裁剪区域大小的新图像,并在该图像上绘图。
下面是一个将裁剪后的图像存储在 BufferedImage 中的示例:
//enter the appropriate type of image for TYPE_FOO
BufferedImage cropped = new BufferedImage(300, 300, BufferedImage.TYPE_FOO);
cropped.getGraphics().drawImage(image,
0, 0, 300, 300, //draw onto the entire 300x300 destination image
100, 100, 400, 400, //draw the section of the image between (100, 100) and (400, 400)
null);
image = cropped;
关于java - 如何使用drawImage()来裁剪图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27628665/