Java 将一个 BufferedImage 与另一个进行比较

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15305037/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 19:10:37  来源:igfitidea点击:

Java Compare one BufferedImage to Another

javabufferedimage

提问by RADXack

I need to compare two buffered images to see if they are the exact same. Simply saying if that equals that doesn't work. My current method is

我需要比较两个缓冲图像以查看它们是否完全相同。简单地说,如果这等于那是行不通的。我目前的方法是

                 { 
                 Raster var1 = Img1.getData();    
                 Raster var2 = Img2.getData();

                 int Data1 = (var1.getDataBuffer()).getSize();
                 int Data2 = (var2.getDataBuffer()).getSize();

                 if (Data1 == Data2)
                         {
                         return true;
                         }
                 else 
                           {
                           return false;
                           }
                 }

But that doesn't really work. What other more reliable way is there?

但这真的行不通。还有什么其他更可靠的方法?

回答by devrobf

The obvious solution would be to compare, pixel by pixel, that they are the same.

显而易见的解决方案是逐个像素地比较它们是否相同。

boolean bufferedImagesEqual(BufferedImage img1, BufferedImage img2) {
    if (img1.getWidth() == img2.getWidth() && img1.getHeight() == img2.getHeight()) {
        for (int x = 0; x < img1.getWidth(); x++) {
            for (int y = 0; y < img1.getHeight(); y++) {
                if (img1.getRGB(x, y) != img2.getRGB(x, y))
                    return false;
            }
        }
    } else {
        return false;
    }
    return true;
}

回答by evanmcdonnal

Yeah, assuming they are both in the same format read them as byte strings and compare the bit strings. If one is a jpg and the other a png this won't work. But I'm assuming equality implies they are the same.

是的,假设它们都采用相同的格式,将它们作为字节串读取并比较位串。如果一个是 jpg,另一个是 png,这将不起作用。但我假设平等意味着它们是相同的。

here's an example on how to do the file reading;

这是有关如何进行文件读取的示例;

http://www.java-examples.com/read-file-byte-array-using-fileinputstream

http://www.java-examples.com/read-file-byte-array-using-fileinputstream

回答by SimmaDahnNah

What about hash codes?

哈希码呢?

img1.getData().hashCode().equals(img2.getData().hashCode())