I want a library that can figure out the dimensions of an image with just the first few bytes. It doesn't have to be perfect. I'm looking for something like this Nodejs library. https://github.com/image-size/image-size
Some image file formats, like GIF, BMP, JPEG and PNG have headers with detailed information in the first few bytes such as the file format, image width & height and resolution (DPI). One library that can make use of that is LEADTOOLS (Disclaimer: I work for its vendor).
I tried 4 different files by truncating the file completely and keeping only a small chunk at the beginning. The following Java code worked with all 4 files:
f = new File("D:/test/tst.jpg.hdr"); RasterCodecs codecs = new RasterCodecs(); ILeadStream stream = LeadStreamFactory.create(f.getAbsolutePath()); CodecsImageInfo imgInfo = codecs.getInformation(stream, false); int w = imgInfo.getWidth(); int h = imgInfo.getHeight();
The library supports dozens of file formats (hundreds if you count sub-types), but not all formats contain full information in the header. For GIF and JPEG, only one KB of data was enough. For BMP and PNG, it needed fewer than 300 bytes.
Although the library isn't free, there's a fully working time-limited trial you can download from the website, and technical support is free even during evaluation.
There are ImageMagick bindings/implementations/APIs available for Java -
im4java - http://im4java.sourceforge.net/
jMagick - http://www.jmagick.org/jmagick-doc/
Both are 5+ years old though, not sure how well done they were, etc.
But ImageMagick rocks on the command line, and it works well for me in PHP.