我的Java代码中有一个byte[]
数组格式的图像。我想要从该数组中提取以下信息。我怎样才能尽快完成。
答案 0 :(得分:12)
使用ImageIO作为缓冲图像读取,然后获取所需的相关内容。请参阅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();
}
}
答案 1 :(得分:5)
要从字节数组中获取图像类型,您可以执行以下操作:
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());
}
以下是我对不同文件的输出:
format name = png
format name = JPEG
format name = gif
它的灵感来自:
Convert Byte Array to image in Java - without knowing the type