Search Tutorials


Image Comparison in Java | JavaInUse



Image Comparison in Java

In this tutorial we compare if two images are equal using the java.awt.image.PixelGrabber class.

The are several constructors for the PixelGrabber class. In below example we use the following Constructor-
public PixelGrabber(Image img, int x, int y, int w, int h, boolean forceRGB)
Here
Image img- the image to retrieve the image data from.
int x - the x coordinate of the upper left corner of the rectangle of pixels to retrieve from the image, relative to the default (unscaled) size of the image
int y- the y coordinate of the upper left corner of the rectangle of pixels to retrieve from the image
int w -the width of the rectangle of pixels to retrieve
int h -the height of the rectangle of pixels to retrieve
boolean forceRGB -forceRGB true if the pixels should always be converted to the default RGB ColorModel

As the name specifies what this class does is takes image as input, grabs the pixels,
and output the pixels data of the image. We get this pixel data for both the images and compare them to
check if they are equal. If equal then then the images are identical.
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.PixelGrabber;

public class CompareImages {

	static void processImage() {

		String file1 = "c://newslider1.jpg";
		String file2 = "c://newslider1.jpg";

		// Load the images
		Image image1 = Toolkit.getDefaultToolkit().getImage(file1);
		Image image2 = Toolkit.getDefaultToolkit().getImage(file2);

		try {

			PixelGrabber grabImage1Pixels = new PixelGrabber(image1, 0, 0, -1,
					-1, false);
			PixelGrabber grabImage2Pixels = new PixelGrabber(image2, 0, 0, -1,
					-1, false);

			int[] image1Data = null;

			if (grabImage1Pixels.grabPixels()) {
				int width = grabImage1Pixels.getWidth();
				int height = grabImage1Pixels.getHeight();
				image1Data = new int[width * height];
				image1Data = (int[]) grabImage1Pixels.getPixels();
			}

			int[] image2Data = null;

			if (grabImage2Pixels.grabPixels()) {
				int width = grabImage2Pixels.getWidth();
				int height = grabImage2Pixels.getHeight();
				image2Data = new int[width * height];
				image2Data = (int[]) grabImage2Pixels.getPixels();
			}

			System.out.println("Pixels equal: "
					+ java.util.Arrays.equals(image1Data, image2Data));

		} catch (InterruptedException e1) {
			e1.printStackTrace();
		}
	}

	public static void main(String args[]) {
		processImage();
	}
}
 
If Pixels are equal then the images are also equal.

See Also

Overriding equals() in Java Internal working of ConcurrentHashMap in Java Java - PermGen space vs Heap space Java - PermGen space vs MetaSpace Implement Counting Sort using Java + Performance Analysis Java 8 Features Java Miscelleneous Topics Java Basic Topics Java- Main Menu