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();
}
}
}
1条答案
按热度按时间kx1ctssn1#
你可以尝试使用
javax.imageio.ImageIO
类: