Extract width, height, color and image type from an array of bytes

I have an image in the byte[] array format in my Java code. I want to get the following information from this array. How can I do this as quickly as possible.

  • Width
  • Height
  • Color (black and white, color or transparent? If color, what is the main color?)
  • Type (this image is PNG, GIF, JPEG, etc.)
+7
source share
2 answers

Use ImageIO to read as a buffered image and then get things you need. See the Java doc at http://docs.oracle.com/javase/6/docs/api/javax/imageio/ImageIO.html .

 import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import javax.imageio.ImageIO; public class Test { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // assuming that picture is your byte array byte[] picture = new byte[30]; InputStream in = new ByteArrayInputStream(picture); BufferedImage buf = ImageIO.read(in); ColorModel model = buf.getColorModel(); int height = buf.getHeight(); } } 
+9
source

To get the image type from an array of bytes , you can do something like:

 byte[] picture = new byte[30]; ImageInputStream iis = ImageIO.createImageInputStream(new ByteArrayInputStream(picture)); Iterator<ImageReader> readers = ImageIO.getImageReaders(iis); while (readers.hasNext()) { ImageReader read = readers.next(); System.out.println("format name = " + read.getFormatName()); } 

Here is the result that I have for different files:

 format name = png format name = JPEG format name = gif 

It was inspired by:

Convert byte array to image in Java - not knowing type

+5
source

All Articles