I'm trying to cut a certain part of image in Java and save it back to disk. Is there a function that cuts the images from X, Y with the specified width and height?
Asked
Active
Viewed 1.2k times
6
-
Have you tried typing "java image crop" in your favourite search engine? Or in the stackoverflow search field? – Jean-François Corbett Oct 25 '11 at 18:51
-
possible duplicate of [How to add 20 pixels of white at the top of an existing image file?](http://stackoverflow.com/questions/7028780/how-to-add-20-pixels-of-white-at-the-top-of-an-existing-image-file) – Cerbrus Sep 24 '14 at 08:50
-
1Why on earth was this closed as "too broad"? There's even already a clear and concise answer posted! – aioobe Nov 06 '15 at 15:20
1 Answers
23
You'd typically
- Create a new
BufferedImage
(dst
below) with the desired width and height. - Get hold of it's
Graphics
object - Load the original .jpeg image (
src
below) - Paint the desired part of that, onto the
BufferedImage
- Write the buffered image out to file using
ImageIO
.
In code:
Image src = ImageIO.read(new File("duke.jpg"));
int x = 10, y = 20, w = 40, h = 50;
BufferedImage dst = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
dst.getGraphics().drawImage(src, 0, 0, w, h, x, y, x + w, y + h, null);
ImageIO.write(dst, "png", new File("duke_cropped.png"));
Given this .jpg...
...It generates this .png:

aioobe
- 413,195
- 112
- 811
- 826