Grayscale image

I'm still having a problem with grayscale image with Java. How can i do this? The format is not so important, but there should be no image compression.

Does anyone know this?

+3
source share
1 answer

This may not be the most elegant method, but it will work:

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;


public class ImageTest {


    public static void main(String[] args) throws IOException {

        int width = 10 // width of your image
        int height = 10 // height of your image

        BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);


        for (int x = 0; x < width; ++x)
        {
            for (int y = 0; y < height; ++y)
            {
                int grayscale = ... // get your greyscale value 0..255 from your array here.
                int colorValue = grayscale | grayscale << 8 | grayscale << 16;
                img.setRGB(x, y, colorValue);
            }

        }

        ImageIO.write(img, "png", new File("output.png"));
    }

}

The colors colorValue consist of r, g, and b (b in low byte, g one before and r one before). Since your image is grayscale, you can simply use the same r, g, and b values ​​for your image so you can just do:

int colorValue = grayscale | grayscale << 8 | grayscale << 16;
+3
source

Source: https://habr.com/ru/post/1731755/


All Articles