【问题标题】:Image formats that preserve rgb value. And store such an image in Java保留 rgb 值的图像格式。并将这样的图像存储在 Java 中
【发布时间】:2018-01-15 22:04:55
【问题描述】:

将图像存储为 JPG 不会保留像素的 RGB 值; PNG 也不起作用。

这是我的问题,我写了一个这样的java程序:

BufferedImage img=ImageIO.read(new File("Pathtoimage"));
//changed the pixel values using getRGB() and setRGB()
ImageIO.write(img,"png","pathToTarget");

然后我写了其他代码来读取像素值,我发现它们是不同的。

如果我不存储图像,一切似乎都很好。但我确实需要以像素完美保留其设置的 RGB 值的方式存储图像。请建议其他文件格式(PNG 和 JPG 不适用)或解决方法。

【问题讨论】:

  • 如果您希望能够完全按原样恢复数据,请不要使用 PNG 和 JPG 都具有的有损压缩算法。跨度>
  • PNG 是无损的,尽管它可以选择支持有损压缩以减小文件大小。您是否进行过任何研究,例如搜索“无损图像格式”?
  • @MattClark PNG 是一种无损格式。是的,它是possiblereduce quality 之前 PNG 编码,但你仍然会得到编码的内容。
  • @SouritChakraborty 你用什么代码来测试 RGB 值是否相等?请注意,BufferedImage.getRGB()/setRGB()总是对 sRGB 颜色空间中的颜色进行操作。如果您的 PNG 文件使用不同的颜色空间,或在使用不同颜色空间的应用程序中进行测试,则这些值将与您设置的不完全相同。

标签: java bufferedimage javax.imageio argb


【解决方案1】:

这是一个 PoC 程序,它创建一个空白图像、设置 RGB 值、将其存储为 PNG 并读回完全相同的值:

public static void main(String[] args) throws IOException {
    BufferedImage image = new BufferedImage(256, 4, BufferedImage.TYPE_INT_ARGB);

    for (int x = 0; x < image.getWidth(); x++) {
        image.setRGB(x, 0, 0x00ffffff | x << 24); // alter alpha
        image.setRGB(x, 1, 0xff000000 | x << 16); // alter red
        image.setRGB(x, 2, 0xff000000 | x <<  8); // alter green
        image.setRGB(x, 3, 0xff000000 | x      ); // alter blue
    }


    File file = File.createTempFile("temp-", ".png");
    if (!ImageIO.write(image, "PNG", file)) {
        System.err.println("Could not write image");
        System.exit(1);
    }

    BufferedImage read = ImageIO.read(file);

    if (read.getWidth() != image.getWidth() || read.getHeight() != image.getHeight()) {
        System.err.println("Dimensions differ!");
        System.exit(1);
    }

    for (int y = 0; y < read.getHeight(); y++) {
        for (int x = 0; x < read.getWidth(); x++) {
            // Uncomment this line, if you want to verify the values
            // System.out.printf("image.getRGB(%3d, %d): #%08x\n", x, y, image.getRGB(x, y));

            if (image.getRGB(x, y) != read.getRGB(x, y)) {
                System.err.printf("pixel differ @ [%3d,%d]: #%08x\n", x, y, read.getRGB(x, y));
            }
        }
    }
}

原始图像与我写回的图像(在 Windows 上使用 Java 1.8.0_131)之间没有区别。

【讨论】:

  • 昨天没用。然而,今天 png 正在工作。我之前曾尝试使用 jpg,但文件可能有问题。但它现在正在工作。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-04
  • 1970-01-01
  • 2015-03-07
  • 2015-10-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多