2011-05-27 94 views
2

我打算在窗口内显示一个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); 
} 

回答

3

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

另外,setPixels应该有足够大的数组来填充栅格的所有波段(A,R,G,B)。直到我将像素的大小增加到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); 
    } 
} 
+0

我已经改变:1)数组大小为28 * 28 * 3(所有0值),2)TYPE_INT_ARGB到TYPE_INT_RGB,3),并在setPixels之后调用image.setData(raster)。但仍然没有图像显示。 – Alexander 2011-05-27 20:42:43

+0

@Alexander,上面是你的代码改变,产生一个白色的图像。无论如何,它适用于我...你是否得到一个JFrame,或者你的程序终止没有任何影响? – Atreys 2011-05-27 20:53:19

+0

谢谢,它的工作原理! – Alexander 2011-05-27 20:56:10

1

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

另外一个(读docs!):你必须调用使用setData

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

()到新的像素放置图像里面,我想。

+0

好,我将其改为TYPE_INT_RGB;但问题依然存在。而且不管数组值如何,图像都不显示,不管它是0还是任何其他值。谢谢。 – Alexander 2011-05-27 20:15:16

+0

对于每个通道,数组必须是size = width * height * 3;其中0..width *高度包含红色,宽度*高度+ 1..2 *宽度*高度值绿色和2 *宽度*高度+ 1 ..宽度*高度* 3的值蓝色的值?谢谢。 – Alexander 2011-05-27 20:24:11

+0

'TYPE_INT_RGB'将三个样本(每个像素一个)打包在一个整数中组成一个像素。 – leonbloy 2011-05-27 20:35:50

相关问题