简体   繁体   English

Java从Bytearray创建BufferedImage

[英]Java creating a BufferedImage from a Bytearray

What I'm trying to do is create a BufferedImage from a byte array. 我想要做的是从字节数组创建BufferedImage。 Here is what I'm doing now: 这是我现在正在做的事情:

    try {
        ByteArrayInputStream in = new ByteArrayInputStream(bytearray);
        BufferedImage bImageFromConvert = ImageIO.read(in);

        Color color = new Color(bImageFromConvert.getRGB((int) local_car.x, (int) local_car.z));
        System.out.println("R :: "+color.getRed() + " B :: "+color.getBlue() + " G :: "+color.getGreen());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

The documentation of ImageIO.read says: ImageIO.read的文档说:

Returns a BufferedImage as the result of decoding a supplied URL with an ImageReader chosen automatically from among those currently registered. 返回一个BufferedImage,作为使用ImageReader解码提供的URL的结果,该ImageReader是从当前注册的URL中自动选择的。 An InputStream is obtained from the URL, which is wrapped in an ImageInputStream. 从URL获得InputStream,该URL包装在ImageInputStream中。 If no registered ImageReader claims to be able to read the resulting stream, null is returned. 如果没有注册的ImageReader声称能够读取结果流,则返回null。

I'm receiving a null pointer exception from ImageIO.read() returning null . 我收到ImageIO.read()返回null的空指针异常。 I am sending my bytearray in the form of RGBA. 我以RGBA的形式发送字节数组。 Why is ImageIO.read returning null? 为什么ImageIO.read返回null?

The ImageIO functions are for reading files and expect the input stream to be in one of the file formats such as PNG or JPG, not for reading simple arrays of rgba. ImageIO函数用于读取文件,并且期望输入流采用PNG或JPG等文件格式之一,而不是用于读取简单的rgba数组。 To read in a simple array try something like: 要读取一个简单的数组,请尝试以下操作:

int width = 256;
int height = 256;
final int bytes_per_pixel = 4;
byte[] raw = new byte[width * height * bytes_per_pixel];
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
IntBuffer intBuf
        = ByteBuffer.wrap(raw)
        .order(ByteOrder.LITTLE_ENDIAN)
        .asIntBuffer();
int[] array = new int[intBuf.remaining()];
intBuf.get(array);
image.setRGB(0, 0, width, height, array, 0, width);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM