簡體   English   中英

如何從 java 中的像素值數組顯示圖像?

[英]How can I display an image from an array of pixels' values in java?

我打算在 window 內顯示一個 28x28 像素的圖像。 像素具有“0”值,所以我希望它顯示一個 window,黑色方塊為 28x28。 但是沒有顯示圖像。 也許數組的數據(我不確定像素值是否必須是 0 到 255 范圍內的 int)必須是其他數據才能顯示圖像。 謝謝!

公共 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()返回柵格的副本 也許如果您在修改柵格后調用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);
  }
}

我不知道這是問題所在,但您使用的是TYPE_INT_ARGB 這包括打包的 integer 中的 Alpha 通道( opacy ),值為 0 表示完全透明。

另一個(閱讀文檔:):

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

我認為,您必須調用 setData() 將新像素放置在圖像中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM