java 从字节数组中提取图像的宽度、高度、颜色和类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17189129/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 01:15:21  来源:igfitidea点击:

Extract image's width, height, color and type from byte array

javaimage

提问by Alireza Noori

I have an image in the format of byte[]array in my Java code. I want the following information extracted from that array. How can I do it as fast as possible.

byte[]我的 Java 代码中有一个数组格式的图像。我想要从该数组中提取以下信息。我怎样才能尽快做到这一点。

  • Width
  • Height
  • Color (black & white, color or transparent? If color, what is the main color?)
  • Type (Is the image PNG, GIF, JPEG, etc.)
  • 宽度
  • 高度
  • 颜色(黑白、彩色还是透明?如果是彩色,主色是什么?)
  • 类型(图像是 PNG、GIF、JPEG 等)

回答by abhinav

Use ImageIO to read as buffered image and then get relevant things which you want. See java doc at http://docs.oracle.com/javase/6/docs/api/javax/imageio/ImageIO.html.

使用 ImageIO 读取缓冲图像,然后获取您想要的相关内容。请参阅http://docs.oracle.com/javase/6/docs/api/javax/imageio/ImageIO.html 上的java 文档。

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();

    }

}

回答by adou600

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 中将字节数组转换为图像 - 不知道类型