简体   繁体   中英

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

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
            }
        }
    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM