I am not sure if my problem is platform specific, but I think it is not.
Because my expirience is based on the Windows specific java.awt.Toolkit and the Windows-Clipboard.
The following example class shows the problem i am faced with.
NOTE: Before running the program, make sure you have no Image in you system clipboard.
If there is no Image in the system clipboard the Program put a new screenshot to it.
Then I get the Clipboard data two times!
All 3 Images are equal! – the original Screenshot and every Image I get from the clipboard.
which is ok.
But now running the program a second time.
NOTE: There is the old screenshot in the clipboard!
The Program generates a new screenshot and get the old one from the clipboard two times.
No Images is equal to any! – The first (new screenshot) should be not equal, it is okay
But every next Image I get is not equal.
Q1: If every next Image I get is not equal, why it was equal at the first time?
Q2: The bigger Question: How can I compare a java.awt.Image to get every next Image equal.
I am looking for an easy and fast comparison of two Images or an easy way to figure out that the clipboard doesn’t has changed.
public class Example {
public static void main( String[] args ) throws Exception {
final Toolkit toolkit = Toolkit.getDefaultToolkit();
final Clipboard clipboard = toolkit.getSystemClipboard();
final Image origImage = new Robot().createScreenCapture( new Rectangle( toolkit.getScreenSize() ) );
if( !clipboard.isDataFlavorAvailable( DataFlavor.imageFlavor )
|| clipboard.getData( DataFlavor.imageFlavor ) == null ) {
clipboard.setContents( new ImageSelection( origImage ), null );
}
Image clipImage1 = (Image)clipboard.getData( DataFlavor.imageFlavor );
Image clipImage2 = (Image)clipboard.getData( DataFlavor.imageFlavor );
System.out.println(origImage.hashCode());
System.out.println(clipImage1.hashCode());
System.out.println(clipImage2.hashCode());
System.out.println(clipImage1.equals( clipImage2 ));
}
public static class ImageSelection implements Transferable {
private Image image;
public ImageSelection(Image image) {
this.image = image;
}
@Override
public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[]{DataFlavor.imageFlavor};
}
@Override
public boolean isDataFlavorSupported(DataFlavor flavor) {
return DataFlavor.imageFlavor.equals(flavor);
}
@Override
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
if (!DataFlavor.imageFlavor.equals(flavor)) {
throw new UnsupportedFlavorException(flavor);
}
return image;
}
}
}
Q1: The object references were the same in the first case.
Q2: here is a way to check the data is equal in the screen shots: