Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 3258
  • Last Modified:

How to compare 2 images using java

How to compare two images are same or not using java.
0
Vineel_Davuluri
Asked:
Vineel_Davuluri
2 Solutions
 
objectsCommented:
compare the two source byte arrays

0
 
a_bCommented:
You need to convert the file into a byte array and then compare those byte arrays.
0
 
nkiggsCommented:
You'll need to import the following libraries:

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

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("Are they equal?: " + java.util.Arrays.equals(data1, data2));
} 
catch (InterruptedException e1) {
	e1.printStackTrace();
}

Open in new window

0
 
Thomas4019Commented:
I would use this code
import java.io.File;
import java.awt.image.*;
import javax.imageio.*;
 
class Test
{
	public boolean imagesEqual(File f1,File f2)
	{
		BufferedImage i1,i2;
 
		try
		{
			i1 = ImageIO.read(f1);
			i2 = ImageIO.read(f2);
		}
		catch(Exception e){ e.printStackTrace(); return false; }
 
		if(i1.getWidth() != i2.getWidth() || i1.getHeight() != i2.getHeight())
			return false;
 
		for(int x = 0; x < i1.getWidth(); x++)
			for(int y = 0; y < i1.getWidth(); y++)
				if(i1.getRGB(x,y) != i2.getRGB(x,y))
					return false;
 
		return true;
	}
}

Open in new window

0

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now