1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.commons.imaging.roundtrip;
19
20 import static org.junit.jupiter.api.Assertions.assertEquals;
21 import static org.junit.jupiter.api.Assertions.assertTrue;
22
23 import java.awt.image.BufferedImage;
24 import java.io.File;
25 import java.io.IOException;
26
27 import org.apache.commons.imaging.internal.Debug;
28 import org.apache.commons.io.FileUtils;
29
30 final class ImageAsserts {
31
32 static void assertFileEquals(final File a, final File b) throws IOException {
33 assertTrue(a.exists() && a.isFile());
34 assertTrue(b.exists() && b.isFile());
35 assertEquals(a.length(), b.length());
36
37 final byte[] aData = FileUtils.readFileToByteArray(a);
38 final byte[] bData = FileUtils.readFileToByteArray(b);
39
40 for (int i = 0; i < a.length(); i++) {
41 final int aByte = 0xff & aData[i];
42 final int bByte = 0xff & bData[i];
43
44 if (aByte != bByte) {
45 Debug.debug("a: " + a);
46 Debug.debug("b: " + b);
47 Debug.debug("i: " + i);
48 Debug.debug("aByte: " + aByte + " (0x" + Integer.toHexString(aByte) + ")");
49 Debug.debug("bByte: " + bByte + " (0x" + Integer.toHexString(bByte) + ")");
50 }
51 assertEquals(aByte, bByte);
52 }
53 }
54
55 static void assertImageEquals(final BufferedImage a, final BufferedImage b) {
56 assertImageEquals(a, b, 0);
57 }
58
59 static void assertImageEquals(final BufferedImage a, final BufferedImage b, final int tolerance) {
60 assertEquals(a.getWidth(), b.getWidth());
61 assertEquals(a.getHeight(), b.getHeight());
62
63 for (int x = 0; x < a.getWidth(); x++) {
64 for (int y = 0; y < a.getHeight(); y++) {
65 final int aArgb = a.getRGB(x, y);
66 final int bArgb = b.getRGB(x, y);
67 if (aArgb != bArgb) {
68 if (calculateARGBDistance(aArgb, bArgb) <= tolerance) {
69 continue;
70 }
71 }
72 if (aArgb != bArgb) {
73 Debug.debug("width: " + a.getWidth());
74 Debug.debug("height: " + a.getHeight());
75 Debug.debug("distance: " + calculateARGBDistance(aArgb, bArgb));
76 Debug.debug("x: " + x);
77 Debug.debug("y: " + y);
78 Debug.debug("aArgb: " + aArgb + " (0x" + Integer.toHexString(aArgb) + ")");
79 Debug.debug("bArgb: " + bArgb + " (0x" + Integer.toHexString(bArgb) + ")");
80 }
81 assertEquals(aArgb, bArgb);
82 }
83 }
84 }
85
86 static int calculateARGBDistance(final int a, final int b) {
87 final int aAlpha = 0xff & a >> 24;
88 final int aRed = 0xff & a >> 16;
89 final int aGreen = 0xff & a >> 8;
90 final int aBlue = 0xff & a >> 0;
91 final int bAlpha = 0xff & b >> 24;
92 final int bRed = 0xff & b >> 16;
93 final int bGreen = 0xff & b >> 8;
94 final int bBlue = 0xff & b >> 0;
95 return Math.abs(aAlpha - bAlpha) + Math.abs(aRed - bRed) + Math.abs(aGreen - bGreen) + Math.abs(aBlue - bBlue);
96
97 }
98
99 private ImageAsserts() {
100 }
101 }