How to convert 16 bit grayscale image to RGB image in java?

I am making a desktop application in Java Swing using the Netbeans platform. I want to convert a 16-bit grayscale image to an RGB image. How can i do this?

+1
source share
2 answers

Grayscale is stored in one value, black, while RBG is held in three, red, blue and green. The best you can do with this is a monochrome image, which you can do with the method getRGB(x, y)in the class BufferedImage. Since your input image is in shades of gray, you can take three color values ​​from them because they must be the same. Then use this value for any color you choose to be the basis of monochrome.

Here is an example with red:

public BufferedImage changeToRedMonochrome(BufferedImage grayImage)
{
    int width = grayImage.getWidth();
    int height = grayImage.getHeight()

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

    for (int y=0; y<height; y++)
    {
        for (int x=0; x<width; x++)
        {
            Color grayColor = new Color(grayImage.getRGB);
            int gray = grayColor.getRed();

            int red = (gray > 127) ? 255 : gray/2;
            int blue = (gray > 127 ? gray/2 : 0;
            int green = (gray > 127 ? gray/2 : 0;

            Color redColor = new Color(red, blue, green);
            redImage.setRGB(x, y, redColor);
        }
    }
}

This is not a perfect code, and, of course, you will need to customize it according to your specific needs, but this is one way to make a monochrome image.

+1
source

getRGB/setRGB, Incompl, . , ( , ). , Java BufferedImage.TYPE_USHORT_GRAY BufferedImage.TYPE_INT_RGB:

int width = grayImage.getWidth();
int height = grayImage.getHeight()

BufferedImage newImage = new BufferedImage(
    width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = newImage.getGraphics();  
g.drawImage(grayImage, 0, 0, null);  
g.dispose();  
+1

All Articles