Action disabled: revisions

Resize Image with ImageIO and Graphics2D

Here is how we do it. Note that the try catch exception is omitted here, you need to do it yourself.

  1. Read the image file from storage as InputStream
  2. Read it as BufferedImage
  3. Create a new BufferedImage with new image width, height, and type. Here we assume we scale down 50% of each size of the image.
  4. Create a Graphics2D object from the new BufferedImage.
  5. Use the method Graphics2D.drawImage(…) to draw the input buffered image to the new buffered image
  6. dispose the Graphics2D object.
  7. Save the buffered image to file.
    imageInputStream = new FileInputStream("input.jpg");
    BufferedImage inputBufferedImage =;
    int scaledWidth = (int) (inputBufferedImage.getWidth() * 0.5f);
    int scaledHeight = (int) (inputBufferedImage.getHeight() * 0.5f);
    BufferedImage outputBufferedImage = new BufferedImage(scaledWidth, scaledHeight, memberImage.getType());
    Graphics2D g2d = outputBufferedImage.createGraphics();
    g2d.drawImage(inputBufferedImage, 0, 0, scaledWidth, scaledHeight, null);
    File outputFile = new File("output.jpg");
    ImageIO.write(outputBufferedImage, "jpg", outputFile);
  • java/resize_image_with_imageio_and_graphics2d.txt
  • Last modified: 2020/06/15 11:27
  • by chongtin