I am trying to write text on top of a BufferedImage, then do pixel by pixel comparison with an identical image. However, the comparison always fails. My code looks as follows:
BufferedImage referenceImage = ImageIO.read(new File("reference.jpg"));
BufferedImage image = ImageIO.read(new File("base_image.jpg"));
image.createGraphics().drawString("hello world", 10, 10);
//ImageIO.write(image, "jpg", new File("newimage.jpg"));
//image = ImageIO.read(new File("newimage.jpg"));
assertEquals(image.getWidth(), referenceImage.getWidth());
assertEquals(image.getHeight(), referenceImage.getHeight());
boolean identicalImages = true;
for (int x = 0; x < image.getWidth(); x++) {
for (int y = 0; y < image.getHeight(); y++) {
if (image.getRGB(x, y) != referenceImage.getRGB(x, y)) {
identicalImages = false;
}
}
}
assertTrue(identicalImages);
However, if I uncomment the two commented lines, the code works as expected. I am suspecting it's something that has to do with buffers that need flushing. I tried to flush the image object, but no luck. If anyone could shed some light on what's happening and how to get it to work without having to write the image to disk then read it back, that'd be awesome.