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.
- Read the image file from storage as
InputStream
- Read it as
BufferedImage
- Create a new
BufferedImage
with new image width, height, and type. Here we assume we scale down 50% of each size of the image. - Create a
Graphics2D
object from the new BufferedImage. - Use the method
Graphics2D.drawImage(…)
to draw the input buffered image to the new buffered image - dispose the Graphics2D object.
- Save the buffered image to file.
imageInputStream = new FileInputStream("input.jpg"); BufferedImage inputBufferedImage = ImageIO.read(imageInputStream); 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); g2d.dispose(); File outputFile = new File("output.jpg"); ImageIO.write(outputBufferedImage, "jpg", outputFile);