如何使用drawImage()裁剪图像?

时间:2014-12-23 22:03:12

标签: java crop drawimage

我正在尝试裁剪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提供哪些参数来裁剪我的图片?

1 个答案:

答案 0 :(得分:2)

前四个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;
相关问题