Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grayscaled image

Tags:

java

image

I have still a problem with saving a gray image with Java. How could I do this? The format is not so important, but there should be no image compression.

Does anyone know that?

like image 934
Tim Avatar asked Jun 27 '26 05:06

Tim


1 Answers

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 colorValue is composed of r, g, and b (b on the lowest byte, g one before that, and r one before that). Since your image is greyscale, you can simply use the same r, g and b values for your image, so that's why you can simply do:

int colorValue = grayscale | grayscale << 8 | grayscale << 16;
like image 199
amarillion Avatar answered Jun 28 '26 18:06

amarillion



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!