Image

Imagesparkymark wrote in Imagejava_dev

Strange image comparison problem: X != X

I am trying to compare two images and sometimes find one image does not match itself (or rather the images derived from a single JComponent do not match each other). For a fixed image the following code usually passes the test, but occasionally fails (assertEquals is JUnit function which fails the test if the arguments are not equal).


// Paint a JComponent to an image.
final BufferedImage image = new BufferedImage( referenceDimensions.width,
referenceDimensions.height,
BufferedImage.TYPE_INT_RGB );
final Graphics2D g2d = image.createGraphics();
g2d.setClip( new Rectangle( 0, 0, referenceDimensions.width, referenceDimensions.height ) );
component.paint( g2d );
g2d.dispose();


// Paint the same JComponent to a different image.
final BufferedImage image2 = new BufferedImage( referenceDimensions.width,
referenceDimensions.height,
BufferedImage.TYPE_INT_RGB );
final Graphics2D g2d2 = image2.createGraphics();
g2d2.setClip( new Rectangle( 0, 0, referenceDimensions.width, referenceDimensions.height ) );
component.paint( g2d2 );
g2d2.dispose();

for ( int i = 0; i < image.getWidth(); i++ )
{
for ( int j = 0; j < image.getHeight(); j++ )
{
assertEquals( image2.getRGB( i, j ), image.getRGB( i, j ) );
}
}


I am not doing this on the Swing thread but If I wrap it in SwingUtilities.invokeAndWait it does not help. I also tried turning off antialiasing on the code that generated the image on the component. Does anyone know if it is possible to reliably compare two BufferedImages from JComponents(or what I really want to do, compare an image from a JComponent against a BufferedImage read successfully from a file)?