Skip to content

Instantly share code, notes, and snippets.

@acontal
Created May 10, 2014 10:05
Show Gist options
  • Save acontal/7d0ab2df1f662820f9f5 to your computer and use it in GitHub Desktop.
Save acontal/7d0ab2df1f662820f9f5 to your computer and use it in GitHub Desktop.
[android] Assert that two bitmaps are similar
public static void assertBitmapsAreSimilar(Bitmap expectedBitmap, Bitmap actualBitmap, double tolerance) {
Bitmap reducedExpectedBitmap = Bitmap.createScaledBitmap(expectedBitmap, 32, 32, true);
Bitmap reducedActualBitmap = Bitmap.createScaledBitmap(actualBitmap, 32, 32, true);
int cumulatedColorDistance = 0;
for (int x = 0 ; x < reducedExpectedBitmap.getWidth() ; x++) {
for (int y = 0 ; y<reducedExpectedBitmap.getHeight() ; y++) {
int expectedColor = reducedExpectedBitmap.getPixel(x, y);
int actualColor = reducedActualBitmap.getPixel(x, y);
int expectedRed = Color.red(expectedColor);
int actualRed = Color.red(actualColor);
int expectedBlue = Color.blue(expectedColor);
int actualBlue = Color.blue(actualColor);
int expectedGreen = Color.green(expectedColor);
int actualGreen = Color.green(actualColor);
int colorDistance = Math.abs(expectedRed - actualRed) + Math.abs(expectedBlue - actualBlue) + Math.abs(expectedGreen - actualGreen);
cumulatedColorDistance += colorDistance;
}
}
double difference = 100.0 * cumulatedColorDistance / 3.0 / (32.0 * 32.0) / 255.0;
if (difference > tolerance) {
fail("Difference between the bitmaps: " + difference + "% (>" + tolerance + "%)");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment