英文:
How can I convert an array of pixel values from an image to a PNG binary data without generating the image?
问题
我想将像素数据转换为PNG压缩的二进制数据并存储在数据库中,但我不想生成图像文件。我该如何做?
我尝试使用BufferedImage
来存储我的像素数据,使用com.keypoint.PngEncoder
生成PNG图像的二进制数据,但似乎无法生成仅包含单通道的8位灰度图像。
英文:
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
答案1
得分: 0
你可以尝试使用 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) {
// 假设您的像素数据存储在名为 "pixels" 的二维数组中
byte[][] pixels = {
{0, 127, (byte) 255},
{127, 0, 127},
{(byte) 255, 127, 0}
};
// 创建一个单波段的 8 位灰度配置的 BufferedImage
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; // 将字节转换为无符号值
int rgb = (pixelValue << 16) | (pixelValue << 8) | pixelValue; // 创建 RGB 值
image.setRGB(x, y, rgb); // 在 BufferedImage 中设置像素值
}
}
// 将 BufferedImage 转换为 PNG 压缩的二进制数据
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
ImageIO.write(image, "PNG", outputStream);
byte[] pngData = outputStream.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
}
}
英文:
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();
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论