Is there a simple way to compare BufferedImage ins

2020-01-31 03:16发布

I am working on part of a Java application that takes an image as a byte array, reads it into a java.awt.image.BufferedImage instance and passes it to a third-party library for processing.

For a unit test, I want to take an image (from a file on disk) and assert that it is equal to the same image that has been processed by the code.

  • My expected BufferedImage is read from a PNG file on disk using ImageIO.read(URL).
  • My test code reads the same file into a BufferedImage and writes that to a byte array as PNG to provide to the system under test.

When the system under test writes the byte array to a new BufferedImage I want to assert that the two images are equal in a meaningful way. Using equals() (inherited from Object) doesn’t work (of course). Comparing BufferedImage.toString() values also doesn’t work because the output string includes object reference information.

Does anybody know any shortcuts? I would prefer not to bring in a third-party library for a single unit test in a small part of a large application.

标签: java awt
8条回答
老娘就宠你
2楼-- · 2020-01-31 04:03

working well but not efficient

public static boolean compareImage(File fileA, File fileB) {        
    try {
        // take buffer data from botm image files //
        BufferedImage biA = ImageIO.read(fileA);
        DataBuffer dbA = biA.getData().getDataBuffer();
        int sizeA = dbA.getSize();                      
        BufferedImage biB = ImageIO.read(fileB);
        DataBuffer dbB = biB.getData().getDataBuffer();
        int sizeB = dbB.getSize();
        // compare data-buffer objects //
        if(sizeA == sizeB) {
            for(int i=0; i<sizeA; i++) { 
                if(dbA.getElem(i) != dbB.getElem(i)) {
                    return false;
                }
            }
            return true;
        }
        else {
            return false;
        }
    } 
    catch (Exception e) { 
        e.printStackTrace();
        return  false;
    }
}
查看更多
爱情/是我丢掉的垃圾
3楼-- · 2020-01-31 04:04

I can't think of anything besides a brute force "do loop":

  BufferedImage bi1, bi2, ...
   ...
  Raster r1 = bi1.getData();
  DataBuffer db1 = r1.getDataBuffer();
  if (db1.getSize() != db2.getSize ())
     ...
  for (int i = 0; i < db1.getSize(); i++) {  
    int px = db1.getElem(i);
  }
查看更多
登录 后发表回答