java 如何在不生成图像的情况下将图像中的像素值数组转换为PNG二进制数据?

vlju58qv  于 2023-06-04  发布在  Java
关注(0)|答案(1)|浏览(112)

我想将像素数据转换为PNG压缩的二进制数据并将其存储在数据库中,但不想生成图像文件。我该怎么做?
我尝试使用BufferedImage存储像素数据,使用com.keypoint.PngEncoder生成PNG图像的二进制数据,但似乎无法仅生成单波段8位灰度图像

kx1ctssn

kx1ctssn1#

你可以尝试使用javax.imageio.ImageIO类:

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

相关问题