How to convert 16 bit Gray Scale image to RGB image in java?

笑着哭i 提交于 2020-01-06 04:20:11

问题


I'm making a desktop app in Java Swing using the Netbeans platform. I want to convert a 16 bit gray scale image to an RGB image. How can I do that?


回答1:


Grayscale is held in a single value, black, whereas RBG is held in three, red, blue, and green. The best you can do with this is a monochromatic image, which you can do with the getRGB(x, y) method in the BufferedImage class. Since your input image is in grayscale, you can take any of the three color values from that because they should be the same. Then use that value for whatever color you choose to be the basis of the monochrome.

Here's 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);
        }
    }
}

It's not perfect code, and of course you would need to adjust it to fit your specific needs, but this is one way you could make a monochromatic image.




回答2:


The getRGB/setRGB method described by Incompl should work. But, its performance is rather poor, if I remember correctly (these methods do a lot of work that is unnecessary in this case). I think it would be much faster to draw on the new image and let Java to optimize the conversion from BufferedImage.TYPE_USHORT_GRAY to 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();  


来源:https://stackoverflow.com/questions/11226074/how-to-convert-16-bit-gray-scale-image-to-rgb-image-in-java

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