How to read all the metadata of an image (image format, width and height) in Java. We will the use the awesome metadata-extractor library.
1) Add the dependency
Add the following dependency to your pom.xml:
<dependency>
<groupId>com.drewnoakes</groupId>
<artifactId>metadata-extractor</artifactId>
<version>2.15.0</version>
</dependency>
2) Read the image metadata
For this example, we will use an image from our own website, eazytutorial.com, but you can replace it with any other image that you load as a Java InputStream:
import com.drew.imaging.ImageMetadataReader;
import com.drew.metadata.*;
import java.io.*;
import java.net.URL;
String image = "https://eazytutorial.com/wp-content/uploads/2021/08/26_0.png";
URL url = new URL(image);
InputStream in = new BufferedInputStream(url.openStream());
Metadata metadata = ImageMetadataReader.readMetadata(in);
for (Directory d : metadata.getDirectories()) {
System.out.println(d);
System.out.println("---------------");
for (Tag tag : d.getTags())
System.out.println(tag);
System.out.println();
}
In the console, you will get the following information:
PNG-IHDR Directory (7 tags) --------------- [PNG-IHDR] Image Width - 700 [PNG-IHDR] Image Height - 413 [PNG-IHDR] Bits Per Sample - 8 [PNG-IHDR] Color Type - Indexed Color [PNG-IHDR] Compression Type - Deflate [PNG-IHDR] Filter Method - Adaptive [PNG-IHDR] Interlace Method - No Interlace PNG-gAMA Directory (1 tag) --------------- [PNG-gAMA] Image Gamma - 0.455 PNG-sRGB Directory (1 tag) --------------- [PNG-sRGB] sRGB Rendering Intent - Perceptual PNG-PLTE Directory (1 tag) --------------- [PNG-PLTE] Palette Size - 256 File Type Directory (4 tags) --------------- [File Type] Detected File Type Name - PNG [File Type] Detected File Type Long Name - Portable Network Graphics [File Type] Detected MIME Type - image/png [File Type] Expected File Name Extension - png
So we can see that our image’s format is PNG, the image width is 700 and the image height is 413.
That’s it for this tutorial ! Please leave a reply below if you have questions.