Comparing two Images in Java

Ever wanted to compare two images, but couldn’t get any code? Well, you’re at the right place. Here’s a code in Java to compare two images. The concept used here is an in-built method called PixelGrabber.

Pixel values of the entire image is copied to an array, and arrays of both the images are compared. This comparison returns a true value if both the images are same, and a false value, if not.

Have fun. 🙂

import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.PixelGrabber;

public class Compare {

static void processImage() {

String file1 = "pic1.png";
String file2 = "pic2.png";

Image image1 = Toolkit.getDefaultToolkit().getImage(file1);
Image image2 = Toolkit.getDefaultToolkit().getImage(file2);

try {

PixelGrabber grab1 =new PixelGrabber(image1, 0, 0, -1, -1, false);
PixelGrabber grab2 =new PixelGrabber(image2, 0, 0, -1, -1, false);

int[] data1 = null;

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

int[] data2 = null;

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

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

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

public static void main(String args[]) {
processImage();
}
}

Advertisements

About Manikandan Surendren

A PeopleSoft Techno-functional Consultant. An engineering graduate in Computer Science. Technology Enthusiast. Movie freak. Gadget geek.
This entry was posted in Code. Bookmark the permalink.

2 Responses to Comparing two Images in Java

  1. James saro kadhuwa says:

    great work guy……………….keep up ,and thanks .

  2. khadar shaik says:

    Thats great Thank you for support

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s