简体   繁体   English

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

[英]Java Compare one BufferedImage to Another

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? 还有什么更可靠的方式?

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;
}

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. 如果一个是jpg而另一个是png则不起作用。 But I'm assuming equality implies they are the same. 但我假设平等意味着它们是相同的。

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

哈希码怎么样?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM