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.
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"));