简体   繁体   中英

How to convert a byte array into a PNG image?

How can I convert an array of bytes to a PNG image (not a JPEG)? I know that the process requires a conversion to BufferedImage as a step.

I encountered this problem while coding for steganography.

Let's say you have an array of bytes having length = (image width * image height * 3). First we pack the data into a BufferedImage:

import java.awt.BufferedImage;
byte[] b = (...);
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int y = 0; y < height; y++) {
    for (int x = 0; x < width; x++) {
        int off = (y * width + x) * 3;
        int pix = (b[off] & 0xFF) << 16;  // Red component
        pix |= (b[off + 1] & 0xFF) << 8;  // Green component
        pix |= (b[off + 2] & 0xFF) << 0;  // Blue component
        img.setRGB(x, y, pix);
    }
}

And then we write the PNG image file:

import javax.imageio.ImageIO;
ImageIO.write(img, "png", new File("output.png"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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