在Java中显示一个二维整数数组作为图像

时间:2021-04-08 21:30:01

I'm trying to create an application in Java that will print an image based on an array of integers where each integer represents a color. Is there a straightforward way to accomplish this?

我正在尝试在Java中创建一个应用程序,该应用程序将基于整数数组打印图像,其中每个整数表示一个颜色。有没有一种简单的方法来实现这个目标?

public void displayImage(int[][] arr){
    for(int i = 0; i < arr.length; i++){
        for(int j = 0; j < arr[0].length; j++){
            switch(arr[i][j]){
                case 1:
                //print a gray pixel at (i, j) within a frame
                case 0:
                //print a green pixel at (i, j) within a frame
                case 2:
                //print a white pixel at (i, j) within a frame
            }
        }
    }
}

1 个解决方案

#1


6  

You can use BufferedImage, as shown in this example.

您可以使用BufferedImage,如本例所示。

Addendum: The example cited updates the image's underlying WritableRaster using an int array of color components, but setRGB() is convenient if the color is already available.

附录:引用的示例使用颜色组件的int数组更新图像的底层WritableRaster,但是如果颜色已经可用,setRGB()就很方便了。

#1


6  

You can use BufferedImage, as shown in this example.

您可以使用BufferedImage,如本例所示。

Addendum: The example cited updates the image's underlying WritableRaster using an int array of color components, but setRGB() is convenient if the color is already available.

附录:引用的示例使用颜色组件的int数组更新图像的底层WritableRaster,但是如果颜色已经可用,setRGB()就很方便了。