Displaying a 2D array of integers as an image in Java

有些话、适合烂在心里 提交于 2019-12-11 00:56:26

问题


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?

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:


You can use BufferedImage, as shown in this example.

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.



来源:https://stackoverflow.com/questions/8251791/displaying-a-2d-array-of-integers-as-an-image-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!