Is there no way, using a reference to an instance of type Image
, to force the loading of the corresponding image's data so that e.g. Image.getWidth(ImageObserver)
returns valid data? — For example:
Image image = getImageFromSomewhereElse();
image.load(); // This method doesn't exist but it would be wonderful if it did
Image otherImage = getImageFromYetAnotherPlace();
otherImage.load();
// "compareImages" from <https://stackoverflow.com/a/29886786/1391325>
// "toBufferedImage" from <https://stackoverflow.com/a/13605411/1391325>
if (compareImages(toBufferedImage(image), toBufferedImage(otherImage))){
System.out.println("Yay! Images are the same!");
}
Background
In an existing application, I now need to test if two references to objects of Image
are actually the "same" picture (however that best can be accomplished): In order to do that, I'm trying to do a pixel-by-pixel comparison as suggested in an answer to a related question. In order to do this with the provided solution, however, I need to convert the Image
instances I've got into BufferedImage
instances, e.g. by constructing a new BufferedImage
and then drawing the other image's data onto it as suggested in another post. However, corresponding with acomment posted to the linked answer, this is not possible in my case due to the fact that the images in question have not been loaded yet:
...
Caused by: java.lang.IllegalArgumentException: Width (-1) and height (-1) cannot be <= 0
at java.awt.image.DirectColorModel.createCompatibleWritableRaster(DirectColorModel.java:1016)
java.awt.image.BufferedImage.(BufferedImage.java:333)
...
Unfortunately, the code which creates the Image
instances is quite complicated, so I'm reluctant to start refactoring in order to e.g. instead check if the data used to create the Image
instances is equivalent. Therefore, it would be easiest to simply ensure somehow that each image is loaded before doing the pixel-by-pixel check.