26Dec/08Off
Quick and easy image resizing with Java ImageIO
There are quite a lot of examples of image resizing floating around the web but they all seem to access all sort of hidden features and classes deep inside the JDK to achieve their goal. Here is the most straightforward method that I could come up with - all in all just 5 lines of code. It requires ImageIO and requires Java 1.4 or later to run. If the ImageIO.write() method accepted plain ol' AWT Image arguments it could have been reduced further still to three lines, but you have to give it a BufferedImage instance as input.
The snippet below assumes that there exist the following variables (coloured green in the code):
- an input stream to read from
- a desired width variable (specifying the height as -1 tells the toolkit to preserve the original aspect ratio)
- and an output stream to write the encoded image to.
Sample code:
import java.awt.Image; import java.awt.image.BufferedImage; import javax.imageio.ImageIO;
// ... BufferedImage sourceImage = ImageIO.read(inputStream); Image thumbnail = sourceImage.getScaledInstance(width, -1, Image.SCALE_SMOOTH); BufferedImage bufferedThumbnail = new BufferedImage(thumbnail.getWidth(null), thumbnail.getHeight(null), BufferedImage.TYPE_INT_RGB); bufferedThumbnail.getGraphics().drawImage(thumbnail, 0, 0, null); ImageIO.write(bufferedThumbnail, "jpeg", outputStream);