Sunday, December 12, 2010

checking for Images

I needed to parse a directory and determine which files are images that can be displayed on a panel in my java application. I thought of checking the extensions of files and returning a boolean value of 'true' if they matched those of image files. Examining the folder, I found that somebody had renamed the files to include incorrect file extensions. 'Fake.jpg' was actually a text file. Some image files didn't have extensions at all. 'RealImage' was a .png file. So, checking for extensions wouldn't work.

Then I thought of taking a file and finding out whether the file data bytes started with magic numbers which identify a particular image format .For example ,a PNG file header starts with an 8 bytes signature of 0x89504e470d0a1a0a whereas a GIF89a file has a signature 0x474946383961.

Examining the bytes is the right way to find out the file format. But then ,I didn't want to put too many if then blocks to check every possible image file format that may happen to be in the directory. So I thought of using java's ImageIO class to check for valid images.

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;

public class Utils {
public static boolean isImageFile(String filename) throws IOException{
boolean isImage=false;
FileInputStream is = new FileInputStream(filename);;
ImageInputStream imginstream = ImageIO.createImageInputStream(is);
// get image readers who can read the image format
Iterator iter = ImageIO.getImageReaders(imginstream);
if (iter.hasNext()) {
isImage=true;
}
return isImage;
}
}



No comments:

Post a Comment