我打算在窗口内显示一个28x28像素的图像。像素具有“0”值,所以我预计它会显示一个黑色方块为28x28的窗口。但是没有图像显示。也许数组的数据(我不知道像素值必须是0到255范围内的整数)必须是其他值才能显示图像。谢谢!如何在java中显示像素值的数组中的图像?
公共类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);
}
我已经改变:1)数组大小为28 * 28 * 3(所有0值),2)TYPE_INT_ARGB到TYPE_INT_RGB,3),并在setPixels之后调用image.setData(raster)。但仍然没有图像显示。 – Alexander 2011-05-27 20:42:43
@Alexander,上面是你的代码改变,产生一个白色的图像。无论如何,它适用于我...你是否得到一个JFrame,或者你的程序终止没有任何影响? – Atreys 2011-05-27 20:53:19
谢谢,它的工作原理! – Alexander 2011-05-27 20:56:10