Is there a simple way to compare BufferedImage instances?

前端 未结 8 905
刺人心
刺人心 2020-12-05 19:01

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-p

8条回答
  •  一生所求
    2020-12-05 19:08

    If you want to use Mockito, then you could write a Hamcrest Matcher

    import org.mockito.ArgumentMatcher;
    
    public class BufferedImageMatcher extends ArgumentMatcher {
    
      private final BufferedImage expected;
    
      public BufferedImageMatcher(BufferedImage expected) {
        this.expected = expected;
      }
    
      @Override
      public boolean matches(Object argument) {
        BufferedImage actual = (BufferedImage) argument;
    
        assertEquals(expected.getWidth(), actual.getWidth());
        assertEquals(expected.getHeight(), actual.getHeight());
    
        for (int x = 0; x < actual.getWidth(); x++) {
          for (int y = 0; y < actual.getHeight(); y++) {
            assertEquals(expected.getRGB(x, y), actual.getRGB(x, y));
          }
        }
    
        return true;
      }
    }
    

    and use it like this

    assertThat(actual, new BufferedImageMatcher(expected));
    

提交回复
热议问题