如何在java中显示像素值的数组图像?

我打算在窗口内显示一个28×28像素的图像。 像素的值为“0”,所以我希望它显示一个黑色方块为28×28的窗口。 但是没有显示图像。 也许数组的数据(我不确定像素值是否必须是0到255范围内的int)必须是其他数据才能显示图像。 谢谢!

公共课ASD {

public static Image getImageFromArray(int[] pixels, int width, int height) { BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); WritableRaster raster = (WritableRaster) image.getData(); System.out.println(pixels.length + " " + width + " " + height); raster.setPixels(0,0,width,height,pixels); return image; } public static void main(String[] args) throws IOException { JFrame jf = new JFrame(); JLabel jl = new JLabel(); int[] arrayimage = new int[784]; for (int i = 0; i < 28; i++) { for (int j = 0; j < 28; j++) arrayimage[i*28+j] = 0; } ImageIcon ii = new ImageIcon(getImageFromArray(arrayimage,28,28)); jl.setIcon(ii); jf.add(jl); jf.pack(); jf.setVisible(true); } 

image.getData()返回栅格的副本 。 也许如果在修改栅格后调用image.setData(raster) ,您将看到结果。

此外,setPixels应该有一个足够大的数组来填充栅格的所有波段(A,R,G,B)。 我已经得到一个数组索引超出范围exception,直到我将像素的大小增加到28 * 28 * 4。

对于TYPE_INT_RGB,以下应生成白色图像:

 public class ASD { public static Image getImageFromArray(int[] pixels, int width, int height) { BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); WritableRaster raster = (WritableRaster) image.getData(); raster.setPixels(0, 0, width, height, pixels); image.setData(raster); return image; } public static void main(String[] args) throws IOException { JFrame jf = new JFrame(); JLabel jl = new JLabel(); //3 bands in TYPE_INT_RGB int NUM_BANDS = 3; int[] arrayimage = new int[28 * 28 * NUM_BANDS]; for (int i = 0; i < 28; i++) { for (int j = 0; j < 28; j++) { for (int band = 0; band < NUM_BANDS; band++) arrayimage[((i * 28) + j)*NUM_BANDS + band] = 255; } } ImageIcon ii = new ImageIcon(getImageFromArray(arrayimage, 28, 28)); jl.setIcon(ii); jf.add(jl); jf.pack(); jf.setVisible(true); } } 

我不知道这是问题所在,但您使用的是TYPE_INT_ARGB 。 这包括打包整数中的Alpha通道( opacy ),值0表示完全透明。

另一个(阅读文档 !):

 BufferedImage.getData() : The Raster returned is a copy of the image data is not updated if the image is changed. 

我想你必须调用setData()将新像素放在图像中。