javax.imageio.ImageIO在灰度图像上读取不正确的RGB值 [英] javax.imageio.ImageIO reading incorrect RGB values on grayscale images

查看:91
本文介绍了javax.imageio.ImageIO在灰度图像上读取不正确的RGB值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张图片,称之为grayscale.jpg。现在我在The Gimp中打开该图像并将颜色模式更改为RGB并将其另存为color.jpg。如果我在任何图像查看器中查看grayscale.jpg和color.jpg,它们看起来完全一样。但是如果我用 javax.imageio.ImageIO打开图像

I have an image, call it grayscale.jpg. Now I open that image in The Gimp and change the color mode to RGB and save it as color.jpg. If I view grayscale.jpg and color.jpg in any image viewer, they look exactly the same. But if I open the images with javax.imageio.ImageIO

import javax.imageio.ImageIO;

input = ImageIO.read(new File("grayscale.jpg"));
System.out.format("Grayscale value: %x\n", input.getRGB(200, 200));

input = ImageIO.read(new File("color.jpg"));
System.out.format("Color value: %x\n", input.getRGB(200, 200));

彩色图像将返回正确的值,例如0xff6c6c6c。灰度图像将返回不同的,更轻的,不正确的值,如0xffaeaeae。

The color image will return the correct value, say 0xff6c6c6c. The grayscale image will return a different, lighter, incorrect value like 0xffaeaeae.

Grayscale value: 0xffaeaeae // Incorrect (Lighter)
Color value:     0xff6c6c6c // Correct

换句话说,javax.imageio.ImageIO认为是灰度图像比它们实际上要轻得多。如何准确读取灰度图像?

In other words, javax.imageio.ImageIO thinks grayscale images are much lighter than they actually are. How can I accurately read grayscale images?

编辑

这里有更多上下文。我的用户上传的图片可能是灰度图像。我的Java在服务器上运行,并进行一些非常复杂的图像处理。所以一个理想的解决方案就是修复我的Java代码而不是用命令行工具拼凑一些东西。

Here's more context. My users upload images, which may be grayscale. My Java runs on the server and does some pretty complex image processing. So an ideal solution is to just fix my Java code as opposed to cobbling something together with command line tools.

推荐答案

你的测试是无关紧要,因为你使用的是JPEG,这是有损的。根据压缩,您可能有其他颜色值。所以,尝试使用PNG,这是无损的。

Your test are irrelevant because you are using JPEG, which is lossy. Depending on the compression, you might have other color values. So, try the same with PNG, which is lossless.

您可以使用此图像来测试 javax.imageio 。使用Gimp将此转换为灰度,并确保将其保存为PNG。然后以相同的方式加载(这一个和转换的一个)。并在for循环中比较y轴的所有颜色。

You can use this image to test the correctness of javax.imageio. Convert this one to grayscale with Gimp and make sure you save it as PNG. Then load both (this one and the converted one) the same way. And compare in a for loop all the colors of the y-axis.

示例代码:

BufferedImage inputGrayscale = ImageIO.read(new File("grayscale.png"));    
BufferedImage inputColor = ImageIO.read(new File("color.png"));

for (int i = 0; i < 256; ++i)
{
    System.out.printf(i + "Grayscale value: %x\n", inputGrayscale.getRGB(10, i));
    System.out.printf(i + "Color value: %x\n", inputColor.getRGB(10, i));
    System.out.println();
}

这篇关于javax.imageio.ImageIO在灰度图像上读取不正确的RGB值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆