I intended to display a 28×28 pixels image inside the window. The pixels have “0” value, so I expected it to display a window with a black square of 28×28. 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!
public class 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()returns a copy of the raster.Perhaps if you call
image.setData(raster)after you modify the raster you will see results.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.
For TYPE_INT_RGB, the following should produce a white image: