我正在创建一个接受灰度图像作为输入的简单程序,我只想检索每个像素的颜色信息,将其存储在我称为 PixelClass 的对象数组中。最终目标只是使用上述获取的颜色信息将图像重新绘制为新的 BufferedImage。
用于从给定图像创建像素阵列的代码。
public static PixelClass[][] getPixelArray(BufferedImage bi){
int height = bi.getHeight();
int width = bi.getWidth();
PixelClass[][] pixelArray = new PixelClass[height][width];
for(int i = 0 ; i < height ; i++){
for(int j = 0 ; j < width ; j++){
pixelArray [i] [j] = new PixelClass(bi.getRGB(j, i));
}
}
return pixelArray;
}
用于尝试使用 PixelClass 对象数组重新绘制所述图像的代码
public void paintToPanel(PixelClass [][] pc, int height, int width){
BufferedImage nbi = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
for ( int i = 0 ; i < height ; i++){
for ( int j = 0 ; j < width ; j++){
nbi.setRGB(j, i, pc[i][j].getRGBValue());
}
}
JLabel containerLabel = new JLabel(new ImageIcon(nbi));
containerLabel.setBounds(10,10,nbi.getHeight(), nbi.getWidth());
this.add(containerLabel);
}
原始图片链接
如您所见,图像质量明显下降。生成的图像似乎褪色了。
最佳答案
我建议您使用 MemoryImageSource 类。像这样的东西:
byte[] pixels = // your pixels
ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
int bits[] = new int[] {8};
ColorModel cm = new ComponentColorModel(cs, bits, false, false, Transparency.OPAQUE, DataBuffer.TYPE_BYTE);
MemoryImageSource mis = new MemoryImageSource(width, height, cm, pixels, 0, width);
Image im = Toolkit.getDefaultToolkit().createImage(mis);
关于Java BufferedImage 灰度退化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4760088/