Java 将8位图像转换为4位图像

Java 将8位图像转换为4位图像,java,image,grayscale,Java,Image,Grayscale,当我尝试将我的8位图像转换为4位图像时,有人能看到问题是什么吗 我正在使用此处找到的8位图像进行测试: 你可以知道4位图像应该是什么样子,但我的几乎是纯黑色的 // get color of the image and convert to grayscale for(int x = 0; x <img.getWidth(); x++) { for(int y = 0; y < img.getHeight(); y++) {

当我尝试将我的8位图像转换为4位图像时,有人能看到问题是什么吗

我正在使用此处找到的8位图像进行测试:

你可以知道4位图像应该是什么样子,但我的几乎是纯黑色的

        // get color of the image and convert to grayscale
        for(int x = 0; x <img.getWidth(); x++) {
            for(int y = 0; y < img.getHeight(); y++) {
                int rgb = img.getRGB(x, y);
                int r = (rgb >> 16) & 0xF;
                int g = (rgb >> 8) & 0xF;
                int b = (rgb & 0xF);

                int grayLevel = (int) (0.299*r+0.587*g+0.114*b);
                int gray = (grayLevel << 16) + (grayLevel << 8) + grayLevel;
                img.setRGB(x,y,gray);
            }
        }

您应该使用0xFF而不是0xF,因为0xF仅表示最后四位,而这几乎不会告诉您有关颜色的任何信息,因为在RGB中,颜色是8位的

如果此项工作正常,请尝试:

 // get color of the image and convert to grayscale
        for(int x = 0; x <img.getWidth(); x++) {
            for(int y = 0; y < img.getHeight(); y++) {
                int rgb = img.getRGB(x, y);
                int r = (rgb >> 16) & 0xFF;
                int g = (rgb >> 8) & 0xFF;
                int b = (rgb & 0xFF);

                int grayLevel = (int) (0.299*r+0.587*g+0.114*b);
                int gray = (grayLevel << 16) + (grayLevel << 8) + grayLevel;
                img.setRGB(x,y,gray);
            }
        }

由于该代码已从问题中删除,因此,以下是评论中确认的解决方案:

// get color of the image and convert to grayscale
for(int x = 0; x <img.getWidth(); x++) {
    for(int y = 0; y < img.getHeight(); y++) {
        int rgb = img.getRGB(x, y);

        // get the upper 4 bits from each color component
        int r = (rgb >> 20) & 0xF;
        int g = (rgb >> 12) & 0xF;
        int b = (rgb >> 4) & 0xF;

        int grayLevel = (int) (0.299*r+0.587*g+0.114*b);

        // use grayLevel value as the upper 4 bits of each color component of the new color
        int gray = (grayLevel << 20) + (grayLevel << 12) + (grayLevel << 4);
        img.setRGB(x,y,gray);
    }
}

请注意,生成的图像看起来只有4位灰度,但仍然使用int作为RGB值。

很抱歉,时间太晚了,我已经编写了一段时间了。意思是说8位到4位。我更改了标题好的,但是如果我看到代码,那么从源图像中获取的RGB值将作为常规的24位RGB整数获取。因此,我相信这里显示的是您想要的:答案还显示了如何将RGB int转换为单个组件,请注意代码的差异。您是指&0xFF而不是&0xF吗?您的代码只从每个组件中获取较低的4位。因此,如果我有完整的24位,我不想截断它以便只获取最后4位吗?如果您获取最后4位,则0xF0变为0x0,我假设这不是您想要的。您可以通过另一个4:int r=rgb>>20&0xF的移位来获取上面的4位;等