如何在java中显示像素值的数组图像? [英] How can I display an image from an array of pixels' values in java?
问题描述
我打算在窗口内显示一个28x28像素的图像。像素的值为0,所以我希望它显示一个黑色方块为28x28的窗口。但是没有显示图像。也许数组的数据(我不确定像素值是否必须是0到255范围内的int)必须是其他数据才能显示图像。谢谢!
I intended to display a 28x28 pixels image inside the window. The pixels have "0" value, so I expected it to display a window with a black square of 28x28. But no image is displayed instead. Maybe array's data (I don't know for sure if pixel values must be an int in range from 0 to 255) must be other in order to display the image. Thanks!
公共类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(光栅)
,你会看到结果。
image.getData()
returns a copy of the raster.
Perhaps if you call image.setData(raster)
after you modify the raster you will see results.
另外,setPixels应该有一个足够大的数组来填充栅格的所有波段(A,R,G,B)。我已经得到一个数组索引超出范围的异常,直到我将像素的大小增加到28 * 28 * 4.
Also, setPixels should be given an array large enough to fill all the bands (A, R, G, B) of the raster. I had gotten an array index out of bounds exception until I increased the size of pixels to be 28*28*4.
对于TYPE_INT_RGB,以下应生成白色图像:
For TYPE_INT_RGB, the following should produce a white image:
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);
}
}
这篇关于如何在java中显示像素值的数组图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!