Monday, July 27, 2009

Getting Image Dimensions with Java

Retrieving the dimensions of an image file is a pretty common requirement for a web application. My current project is no exception, and needed to run a validation on uploaded images to ensure their width and height are not too big.

First, I tasked myself with learning to use the javax.imageio api to read through the metadata of an image file. Although this was doable... it was cumbersome. If all you'd like to do is find the image dimensions, you need to iterate through an awful lot of irrelevant information just to find it. After about 80 lines of code, I decided that was not the way to go.

The solution was this:
Image img = new ImageIcon("C:\\prototype.jpg").getImage();
System.out.println("width is "+ img.getWidth(null) );
System.out.println("height is "+ img.getHeight(null) );

Wow. Three lines of code. I think we've got a winner. You'll only need two imports to make this happen:
import java.awt.Image;
import javax.swing.ImageIcon;

This does, obviously, depend on you having the file written to local disk. If you don't (perhaps the file has come through the HTTP Request and is only in RAM), then I'd suggest writing it to the system's temporary file directory, so that you may get the dimensions while it's on the file system, but it will be deleted later. You may get the system's temporary directory like this:
String tempDir = System.getProperty("java.io.tmpdir");

Good luck. =)

No comments: