package utils;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Compare {
public static List<Rectangle> getDifferenceBounds(BufferedImage img1, BufferedImage img2) {
int width = img1.getWidth();
int height = img1.getHeight();
List<Rectangle> diffBoundsList = new ArrayList<>();
// Initialize bounds with invalid values
int minX = Integer.MAX_VALUE;
int minY = Integer.MAX_VALUE;
int maxX = Integer.MIN_VALUE;
int maxY = Integer.MIN_VALUE;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int pixel1 = img1.getRGB(x, y);
int pixel2 = img2.getRGB(x, y);
if (pixel1 != pixel2) {
minX = Math.min(minX, x);
minY = Math.min(minY, y);
maxX = Math.max(maxX, x);
maxY = Math.max(maxY, y);
}
}
}
int diffWidth = maxX - minX + 1;
int diffHeight = maxY - minY + 1;
Rectangle rectangle = new Rectangle(minX, minY, diffWidth, diffHeight);
diffBoundsList.add(rectangle);
return diffBoundsList;
}
public static BufferedImage getDifferenceImage(BufferedImage img1, BufferedImage img2) {
int differentPixelCount = 0;
// convert images to pixel arrays...
final int w1 = img1.getWidth(),
h1 = img1.getHeight(),
w2 = img2.getWidth(),
h2 = img2.getHeight(),
highlight = Color.MAGENTA.getRGB();
if (w1 != w2 || h1 != h2){
System.out.println("Two picture does not match another! No difference!");
System.exit(1);
}
final int[] p1 = img1.getRGB(0, 0, w1, h1, null, 0, w1);
final int[] p2 = img2.getRGB(0, 0, w2, h2, null, 0, w1);
// compare img1 to img2, pixel by pixel. If different, highlight img1's pixel...
for (int i = 0; i < p1.length; i++) {
if (p1
!= p2) {
p1 = highlight;
differentPixelCount++;
}
}
if (differentPixelCount == 0) {
System.out.println("Two picture matches another! No difference!");
System.exit(1);
}
// save img1's pixels to a new BufferedImage, and return it...
// (May require TYPE_INT_ARGB)
BufferedImage out = new BufferedImage(w1, h1, BufferedImage.TYPE_INT_RGB);
List<Rectangle> recs = getDifferenceBounds(img1, img2);
for(Rectangle rec : recs){
out.setRGB(0, 0, w1, h1, p1, 0, w1);
Graphics2D g2d = out.createGraphics();
g2d.setColor(Color.BLUE);
g2d.drawOval(rec.x - 10, rec.y - 10, rec.width + 20, rec.height + 20);
}
return out;
}
public static void main(String[] args) throws IOException {
ImageIO.write(
getDifferenceImage(
ImageIO.read(new File("C\Users\\LENOVO\\IdeaProjects\\Example\\src\\test\\resources\\expectedImage\\image.png")),
ImageIO.read(new File("C\Users\\LENOVO\\IdeaProjects\\Example\\src\\test\\resources\\image.png"))),
"png",
new File("C\Users\\LENOVO\\IdeaProjects\\Example\\src\\test\\resources\\image3.png"));
}
}
a coi thế này hợp lý chưa