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
-
Is this required to be able to work for every image type or just specific ones? Any restrictions on licence, price, etc?– Steve BarnesCommented Dec 21, 2017 at 8:24
-
An optimistic response is fine, but the more image types, the better, hoping for a less restriction license and free– fuzzycuffsCommented Dec 21, 2017 at 18:45
-
Are you open about writing it yourself? What the js library you linked is doing looks simple enough that porting should not be overly difficult.– kutschkemCommented Aug 6, 2018 at 13:10
3 Answers
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.
Standard Java ImageIO (comes with the JDK) can find image dimensions from image header without decoding the image. No need for extra dependencies for the most common formats.
try (ImageInputStream stream = ImageIO.createImageInputStream(input)) {
ImageReader reader = ImageIO.getImageReaders(stream).next(); // TODO: Handle unsupported format
reader.setInput(stream);
int width = reader.getWidth(0);
int height = reader.getHeight(0);
// ...
reader.dispose();
}
Java ImageIO has support for BMP, GIF, JPEG, PNG and TIFF (from Java 9) as standard. 3rd party plugins exists for most popular image formats.