This code will compare pixel from base image with other image.
- If both pixel at location (x,y) are same then add same pixel in result image without change. Otherwise it modifies that pixel and add to our result image.
- In case of baseline image height or width is larger than other image then it will add red color for extra pixel which is not available in other images.
- Both image file format should be same for comparison.
- Code will use base image file format to create resultant image file.
This code will highlight color change in image and place-change of character in image.
Code for image comparison (pixel-by-pixel).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; public class ImageCompMain { public static void main(String[] args) throws IOException { String baseFile = "D:/imageA.PNG"; String changeFile = "D:/imageB.PNG"; //Call method to compare above images. compareWithBaseImage(new File(baseFile), new File(changeFile), "Comp_Result_Sol03"); } public static void createPngImage(BufferedImage image, String fileName) throws IOException { ImageIO.write(image, "png", new File(fileName)); } public static void createJpgImage(BufferedImage image, String fileName) throws IOException { ImageIO.write(image, "jpg", new File(fileName)); } public static void compareWithBaseImage(File baseImage, File compareImage, String resultOfComparison) throws IOException { BufferedImage bImage = ImageIO.read(baseImage); BufferedImage cImage = ImageIO.read(compareImage); int height = bImage.getHeight(); int width = bImage.getWidth(); BufferedImage rImage = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { try { int pixelC = cImage.getRGB(x, y); int pixelB = bImage.getRGB(x, y); if (pixelB == pixelC ) { rImage.setRGB(x, y, bImage.getRGB(x, y)); } else { int a= 0xff | bImage.getRGB(x, y)>>24 , r= 0xff & bImage.getRGB(x, y)>>16 , g= 0x00 & bImage.getRGB(x, y)>>8, b= 0x00 & bImage.getRGB(x, y); int modifiedRGB=a<<24|r<<16|g<<8|b; rImage.setRGB(x,y,modifiedRGB); } } catch (Exception e) { // handled hieght or width mismatch rImage.setRGB(x, y, 0x80ff0000); } } } String filePath = baseImage.toPath().toString(); String fileExtenstion = filePath.substring(filePath.lastIndexOf('.'), filePath.length()); if (fileExtenstion.toUpperCase().contains("PNG")) { createPngImage(rImage, resultOfComparison + fileExtenstion); } else { createJpgImage(rImage, resultOfComparison + fileExtenstion); } } } |
Sample images that are used for comparison.
Comparison Result:
|
---|