Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

In Java, how can I convert an array of pixel values from a 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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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();
        }
    }
}

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading