2018-02-01 22:39:57 -05:00
|
|
|
import java.awt.image.BufferedImage;
|
|
|
|
import java.io.File;
|
|
|
|
import java.io.IOException;
|
|
|
|
|
|
|
|
import javax.imageio.ImageIO;
|
2018-01-31 08:12:02 -05:00
|
|
|
|
|
|
|
public class Item {
|
2018-02-01 22:39:57 -05:00
|
|
|
|
|
|
|
private BufferedImage itemImage;
|
2018-02-02 00:03:14 -05:00
|
|
|
private int minimumNumberOfMatchingPixels;
|
2018-02-01 22:39:57 -05:00
|
|
|
|
|
|
|
public Item(String itemDirectoryPath, String itemName) throws IOException {
|
|
|
|
initializeImage(itemDirectoryPath, itemName);
|
2018-02-02 00:03:14 -05:00
|
|
|
this.minimumNumberOfMatchingPixels = 100;
|
2018-02-01 22:39:57 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
private void initializeImage(String itemDirectoryPath, String itemName) throws IOException {
|
|
|
|
File itemImageFile = new File(joinPathWithFileName(itemDirectoryPath, itemName));
|
|
|
|
this.itemImage = ImageIO.read(itemImageFile);
|
|
|
|
}
|
|
|
|
|
|
|
|
private String joinPathWithFileName(String itemDirectoryPath, String itemName) {
|
|
|
|
return (itemDirectoryPath + itemName);
|
|
|
|
}
|
2018-01-31 08:12:02 -05:00
|
|
|
|
2018-02-01 22:39:57 -05:00
|
|
|
public boolean itemMatchesImage(BufferedImage itemImageToCompare) {
|
|
|
|
if (imagesAreTheSameSize(itemImageToCompare)) {
|
2018-02-02 00:03:14 -05:00
|
|
|
return imagesMatch(itemImageToCompare, 5);
|
2018-02-01 22:39:57 -05:00
|
|
|
}
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
private boolean imagesAreTheSameSize(BufferedImage itemImageToCompare) {
|
|
|
|
return (itemImage.getWidth() == itemImageToCompare.getWidth()) && (itemImage.getHeight() == itemImageToCompare.getHeight());
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
private boolean imagesMatch(BufferedImage itemImageToCompare, int pixelTolerance) {
|
2018-02-02 00:03:14 -05:00
|
|
|
int numberOfMatchingPixels = 0;
|
2018-02-01 22:39:57 -05:00
|
|
|
for (int row = 0; row < itemImageToCompare.getWidth(); row++) {
|
|
|
|
for (int col = 0; col < itemImageToCompare.getHeight(); col++) {
|
|
|
|
if (pixelsAreWithinRGBTolerance(itemImage.getRGB(row, col), itemImageToCompare.getRGB(row, col))) {
|
2018-02-02 00:03:14 -05:00
|
|
|
numberOfMatchingPixels++;
|
2018-02-01 22:39:57 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2018-02-02 00:03:14 -05:00
|
|
|
return (numberOfMatchingPixels > this.minimumNumberOfMatchingPixels);
|
2018-02-01 22:39:57 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
private boolean pixelsAreWithinRGBTolerance(int rgb1, int rgb2) {
|
|
|
|
int[] colors1 = getRGBValuesFromPixel(rgb1);
|
|
|
|
int[] colors2 = getRGBValuesFromPixel(rgb2);
|
|
|
|
for (int i = 0; i < 3; i++) {
|
|
|
|
if (Math.abs(colors1[i] - colors2[i]) > 5) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
private int[] getRGBValuesFromPixel(int pixel) {
|
|
|
|
int[] colors = {(pixel)&0xFF, (pixel>>8)&0xFF, (pixel>>16)&0xFF, (pixel>>24)&0xFF};
|
|
|
|
return colors;
|
|
|
|
}
|
2018-01-31 08:12:02 -05:00
|
|
|
}
|