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 usingImageIO.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.
If speed is an issue, and both
BufferedImages
are of the same bit-depth, arrangement, etc. (which seems like it must be true here) you can do this:figure out which type it is, e.g. a
DataBufferInt
do a few "sanity checks" for equals on the sizes and banks of the DataBuffers, then loop
This is close to as fast as you can get cause you are grabbing a chunk of the data at a time, not one at a time.
This is the best approach. No need to keep a variable to tell whether the image is still equal. Simply return false immediately when the condition if false. Short-circuit evaluation helps save time looping over pixels after the comparison fails as is the case in trumpetlick's answer.
I changed function that equals by pixels in Groovy, may be helpful:
If you want to use Mockito, then you could write a Hamcrest Matcher
and use it like this
You can write that image via
imageio
through anOutputStream
to abyte[]
. In my code, it looks more or less like this:You could write your own routine for comparison!
This would be one way!!!