Search code examples
javapng

How can I convert an array of pixel values from an image to a PNG binary data without generating the image?


I want to convert pixel data to PNG-compressed binary data and store it in a database, but I don't want to generate an image file. How can I do this?

I tried using BufferedImage to store my pixel data and com.keypoint.PngEncoder to generate binary data for PNG images, but couldn't seem to generate only single-band 8-bit grayscale images


Solution

  • You can try to use the javax.imageio.ImageIO class:

    import javax.imageio.ImageIO;
    import java.awt.image.BufferedImage;
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    
    public class PixelToPNG {
        public static void main(String[] args) {
            // Assuming you have your pixel data stored in a 2D array called "pixels"
            byte[][] pixels = {
                    {0, 127, (byte) 255},
                    {127, 0, 127},
                    {(byte) 255, 127, 0}
            };
    
            // Create a BufferedImage with single-band 8-bit grayscale configuration
            BufferedImage image = new BufferedImage(pixels[0].length, pixels.length, BufferedImage.TYPE_BYTE_GRAY);
            for (int y = 0; y < pixels.length; y++) {
                for (int x = 0; x < pixels[y].length; x++) {
                    int pixelValue = pixels[y][x] & 0xFF; // Convert byte to unsigned value
                    int rgb = (pixelValue << 16) | (pixelValue << 8) | pixelValue; // Create RGB value
                    image.setRGB(x, y, rgb); // Set pixel value in the BufferedImage
                }
            }
    
            // Convert the BufferedImage to PNG-compressed binary data
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            try {
                ImageIO.write(image, "PNG", outputStream);
                byte[] pngData = outputStream.toByteArray();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }