问题
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