[英]Extract image's width, height, color and type from byte array
I have an image in the format of byte[]
array in my Java code. 我的Java代码中有一个byte[]
数组格式的图像。 I want the following information extracted from that array. 我想要从该数组中提取以下信息。 How can I do it as fast as possible. 我怎样才能尽快完成。
Use ImageIO to read as buffered image and then get relevant things which you want. 使用ImageIO作为缓冲图像读取,然后获取所需的相关内容。 See java doc at http://docs.oracle.com/javase/6/docs/api/javax/imageio/ImageIO.html . 请参阅http://docs.oracle.com/javase/6/docs/api/javax/imageio/ImageIO.html上的 java doc。
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();
}
}
To get the image type from the byte array , 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 output I have for different files: 这是我对不同文件的输出:
format name = png
format name = JPEG
format name = gif
It was inspired from: 它的灵感来自:
Convert Byte Array to image in Java - without knowing the type 将字节数组转换为Java中的图像 - 不知道类型
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.