InJustice47 - 2 years ago 132
Java Question

# Java: Comparing two Bufferedimages using loops

When i want to check if two Bufferedimages are the same, i can simply compare them pixel by pixel using these two loops:

``````boolean bufferedImagesEqual(BufferedImage img1, BufferedImage img2) {
if (img1.getWidth() == img2.getWidth() && img1.getHeight() == img2.getHeight()) {
for (int x = 0; x < img1.getWidth(); x++) {
for (int y = 0; y < img1.getHeight(); y++) {
if (img1.getRGB(x, y) != img2.getRGB(x, y))
return false;
}
}
} else {
return false;
}
return true;
}
``````

I took this from : Here

But I also want this to work if
`img2`
is rotated by
`90 or 270`
degrees. I tried swtiching
`x`
and
`y`
, using combinations like
`img2.getWidth()-x`

in the second
`.getRGB()`
but none of it seems to work.

I know it may not be the hardest problem in the world but i cannot seem to figure it out.

Any help would be greatly appreciated.

I think it is unavoidable to perform the "2-loops" 3 times: one for 0 degree rotation, the second 90 and the third 270:

For 90 degrees: (assert img1.getWidth()==img2.getHeight() && img1.getHeight()==img2.getWidth())

``````for (int x = 0; x < img1.getWidth(); x++) {
for (int y = 0; y < img1.getHeight(); y++) {
if (img1.getRGB(x, y) != img2.getRGB(img1.getHeight() - 1 - y, x))
return false;
}
}
``````

For 270 degrees: (assert img1.getWidth()==img2.getHeight() && img1.getHeight()==img2.getWidth())

``````for (int x = 0; x < img1.getWidth(); x++) {
for (int y = 0; y < img1.getHeight(); y++) {
if (img1.getRGB(x, y) != img2.getRGB(y, img1.getWidth() - 1 - x))
return false;
}
}
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download