0

I have an image's data in an array of bytes (byte[] imgData). I'd like to get its metadata such as:

  • Dimensions
  • Color / Black & White
  • File type (JPEG, PNG, ...)
  • ...

How can I do this? If there's a library I have to know about, please let me know.

I've found Getting metadata from JPEG in byte array form but it says it's related to JPEG images. I want to do this for all images. Also, it doesn't explain how it works.

Community
  • 1
  • 1
Alireza Noori
  • 14,961
  • 30
  • 95
  • 179

2 Answers2

0

Unfortunately, it is not practical to support every image format ever conceived (or about to be thought of). There are simply too many. Using standard J2SE we can cater for the types returned in the String[] obtained from ImageIO.getReaderFileSuffixes(). As seen in this answer.

Adding Java Advanced Imaging to the run-time adds support (via Service Provider Interface) for further image formats, including TIFF.

Community
  • 1
  • 1
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • Thanks for the answer. I'm sorry but how does this answer my question? Just to clarify, I'm not looking for "every image format ever conceived". Just the more used ones would suffice. – Alireza Noori May 20 '13 at 12:35
0

You can do this using normal ImageIO:

ImageInputStream stream = ImageIO.createImageInputStream(new ByteArrayInputStream(imgData); // assuming imgData is byte[] as in your question
Iterator<ImageReader> readers = ImageIO.getImageReaders(stream);
if (!readers.hasNext()) {
     // We don't know about this format, give up
}

ImageReader reader = readers.next();
reader.setInput(stream);

// Now query for the properties you like

// Dimensions:
int width = reader.getWidth(0);
int height = reader.getHeight(0);

// File format (you can typically use the first element in the array):
String[] formats = reader.getOriginatingProvider().getFormatNames();

// Color model (note that this will return null for most JPEGs, as Java has no YCbCr color model, but at least this should get you going):
ImageTypeSpecifier type = reader.getRawImageType(0);
ColorModel cm = type.getColorModel();

// ...etc...

For more advanced properties you may want to look into IIOMetadata, but I find that most of the time I don't need it (and the API is just too much hassle).

You are still limited to the formats listed by ImageIO.getReaderFileSuffixes(), as Andrew mentioned. You might need to add plugins for specific formats.

Harald K
  • 26,314
  • 7
  • 65
  • 111