Saturday, 23 November 2013

Loading, cropping, saving an image in Java

You'd typically
  1. Create a new BufferedImage with the desired width and height.
  2. Get hold of it's Graphics object
  3. Load the original .jpeg image
  4. Paint the desired part of that, onto the BufferedImage
  5. Write the buffered image out to file using ImageIO.
In code:
Image orig = File("duke.jpg"));

int x = 10, y = 20, w = 40, h = 50;

BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
bi.getGraphics().drawImage(orig, 0, 0, w, h, x, y, x + w, y + h, null);

ImageIO.write(bi, "png", new File("duke_cropped.png"));
Given this .jpg...
...It generates this .png:
Post a Comment