6

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?

RADXack
  • 1,032
  • 3
  • 11
  • 17
  • 2
    Note: instead of this: `if (i1 == i2){ return true; } else { return false; }` always do this: `return (i1 == i2);`. This won't solve your problem in this case, but it's much cleaner looking. – Cory Kendall Mar 08 '13 at 23:28
  • 1
    Possible duplicate of [Is there a simple way to compare BufferedImage instances?](http://stackoverflow.com/questions/11006394/is-there-a-simple-way-to-compare-bufferedimage-instances) – N Kumar Oct 20 '15 at 18:23

3 Answers3

26

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;
}
Nicholas DiPiazza
  • 10,029
  • 11
  • 83
  • 152
devrobf
  • 6,973
  • 2
  • 32
  • 46
1

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.

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

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

evanmcdonnal
  • 46,131
  • 16
  • 104
  • 115
-3

What about hash codes?

img1.getData().hashCode().equals(img2.getData().hashCode())
  • 3
    It's not save to assume that data is the same if the hashcode is the same. You still have to compare the actual data – doerig Jan 04 '17 at 16:15
  • Worse yet: Both `BufferedImage` and `BufferedImage.getData()` return different hashes for the same data. They don't implement `hashCode()` – Mark Jeronimus May 19 '22 at 13:01