// (c): Tuomas J. Lukka package gzz.util; import java.io.*; import java.awt.Dimension; /** Methods for determining sizes of image files. * Initially, only PNG is supported. */ public class ImageSize { private static int ub(byte b) { if(b < 0) return b + 256; return b; } /** Big-endian long. */ private static int belong(byte[] b) { return ub(b[0]) * 256 * 256 * 256 + ub(b[1]) * 256 * 256 + ub(b[2]) * 256 + ub(b[3]); } /** Read the size of an image file. */ static public Dimension readSize(File f) { try { FileInputStream is = new FileInputStream(f); byte[] in = new byte[4]; is.read(in); if(ub(in[0]) == 0x89 && ub(in[1]) == 'P' && ub(in[2]) == 'N' && ub(in[3]) == 'G' ) { // It's PNG. We know this. is.skip(12); is.read(in); int width = belong(in); is.read(in); int height = belong(in); return new Dimension(width, height); } return null; } catch(IOException e) { return null; } } }