user4267868
user4267868

Reputation: 45

How can I use drawImage() to crop an image?

I'm trying to crop a 500x500 image to only have the 300x300 rectangle in the center, like so:

   Original  Image              
+-------------------+        +-------------------+
|     500 x 500     |        |     Crop Area     |
|                   |        |   +-----------+   |
|                   |        |   | 300 x 300 |   |
|                   |        |   |           |   |
|                   |        |   |           |   | 
|                   |        |   +-----------+   |     
|                   |        |                   |
+-------------------+        +-------------------+

I see that Graphics.drawImage() with 8 int parameters says that it will draw an area of the image, which seems appropriate for drawing only the cropped area of the image, but when I tried image.getGraphics().drawImage(image, 0, 0, 500, 500, 100, 100, 400, 400, null); it didn't correctly crop the image.

What parameters should I give to drawImage to crop my image?

Upvotes: 1

Views: 2619

Answers (1)

Vitruvie
Vitruvie

Reputation: 2337

The first four int parameters represent the rectangular section of the image you want to draw onto (the destination image), and the last four represent the rectangular section of the image you're drawing (the source image). If these rectangles are not the same size, the source image will be rescaled (grown or shrunk) to fit the destination image. Your attempt with drawImage(image, 0, 0, 500, 500, 100, 100, 400, 400, null) doesn't quite work because after you get the correct region of the image, you grow it to fit over the entire image. Because you want to crop your image--changing its dimensions--you must create a new Image that is the right size for the cropped area, and draw onto that image.

Here's an example that stores your cropped image in a 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;

Upvotes: 2

Related Questions