Dev
Dev

Reputation: 127

Convert byte array to Image

I have a byte array which size is 640*480*3 and its byte order is r,g,b. I'm trying to convert it into Image. The following code doesn't work:

BufferedImage img = ImageIO.read(new ByteArrayInputStream(data));

with the excepton

Exception in thread "main" java.lang.IllegalArgumentException: image == null!
at javax.imageio.ImageTypeSpecifier.createFromRenderedImage(ImageTypeSpecifier.java:925)
at javax.imageio.ImageIO.getWriter(ImageIO.java:1591)
at javax.imageio.ImageIO.write(ImageIO.java:1520)

I also tried this code:

ImageIcon imageIcon = new ImageIcon(data);
Image img = imageIcon.getImage();
BufferedImage bi = new BufferedImage(img.getWidth(null),img.getHeight(null),BufferedImage.TYPE_3BYTE_BGR); //Exception

but unsuccessfully:

Exception in thread "main" java.lang.IllegalArgumentException: Width (-1) and height (-1) must be > 0

How can I receive the Image from this array?

Upvotes: 3

Views: 3007

Answers (1)

Durandal
Durandal

Reputation: 20059

A plain byte array is not a gnerally recognized image format. You have to code the conversion yourself. Luckily its not very hard to do:

int w = 640;
int h = 480;
BufferedImage i = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
for (int y=0; y<h; ++y) {
    for (int x=0; x<w; ++x) {
        // calculate index of pixel
        // depends on exact organization of image
        // sample assumes linear storage with r, g, b pixel order
        int index = (y * w * 3) + (x * 3);
        // combine to RGB format
        int rgb = ((data[index++] & 0xFF) << 16) |
                  ((data[index++] & 0xFF) <<  8) |
                  ((data[index++] & 0xFF)      ) |
                  0xFF000000;
        i.setRGB(x, y, rgb);
    }
}

The exact formula for pixel index depends on how you organized the data in the array - which you didn't really specify precisely. The prinicple is always the same though, combine the R, G, B value into an RGB (ARGB to be precise) value and put it in the BufferedImage using setRGB() method.

Upvotes: 2

Related Questions