This script compares two jpg images which are the same size and prints the difference into a third file.
#!/usr/bin/perl #Name: jpg_compare_diff.pl # #Written by: Balazs, Lendvay (ITFanatic :) ) # #Purpose: compare two images (same size) and print the difference to a third file # #The script can be downloaded from "ITFanatic.com" and it is absolutely FREE, #you can redistribute it and/or modify it under the same terms as Perl itself. (I think:) ) #This script comes with NO WARRANTY of any kind. (I am sure! :) ) #I cannot guarantee that this works in your environment, and I am not responsible #for any harm it may cause on your computer. (I hope it won't cause harm at all :) ) use strict; use GD; use Image::Size; #two input files my $img1="p1.jpg"; my $img2="p2.jpg"; #output file my $outfile="diff.png"; #determine the size of the image my ($size_x,$size_y)=&size($img1); print "size1: $size_x $size_y\n"; &compare_jpgs($img1,$img2,$outfile); #this determines the size of the image sub size() { my ($img0)=@_; my ($size_x, $size_y) = Image::Size::imgsize($img0); return ($size_x,$size_y); } #this reads a jpg's rgb values sub read_jpg() { my ($img0)=@_; #READ RGB values #print "Opening image\n"; my ($size_x0,$size_y0)=&size($img0); my $image = newFromJpeg GD::Image($img0) || die "Unable to open image\n"; #my %data= (); foreach my $w (0..$size_x0) { foreach my $h (0..$size_y0) { my $index = $image->getPixel($w,$h); my ($r,$g,$b) = $image->rgb($index); #print RGB values print "RGB: ($r;$g;$b)\n"; } } } #this subroutine compares the rgb values of the two images #and prints the result to a third file sub compare_jpgs() { my ($img0,$img1,$out)=@_; print "Comparing $img0 and $img1\n"; #determine sizes my ($size_x0,$size_y0)=&size($img0); my $image0 = newFromJpeg GD::Image($img0) || die "Unable to open image\n"; #determine sizes my ($size_x1,$size_y1)=&size($img1); my $image1 = newFromJpeg GD::Image($img1) || die "Unable to open image\n"; #compare the sizes and exit if they are not equal if (($size_x0!=$size_x1) || ($size_y0!=$size_y1)) { print "Compare: Size does not match\n"; exit(1); } else { print "Size matches...continuing\n"; } #open the output file open OUT, ">$out" or die "Cannot open $out for write :$!"; binmode STDOUT; my $image = new GD::Image($size_x, $size_y); my $color; foreach my $w (0..$size_x0) { foreach my $h (0..$size_y0) { my $index0 = $image0->getPixel($w,$h); #get rgb values my ($r0,$g0,$b0) = $image0->rgb($index0); #print "RGB: ($r;$g;$b)\n"; my $index1 = $image1->getPixel($w,$h); #get rgb values my ($r1,$g1,$b1) = $image1->rgb($index1); #compare RGB values if (($r0 != $r1) || ($g0 != $g1) || ($b0 != $b1)) { # print "Difference at: $w:$h pic1: ($r0,$g0,$b0) pic2: ($r1,$g1,$b1)\n"; $color = $image->colorAllocate($r0, $g0, $b0); $image->setPixel($w,$h,$color); } } } print OUT $image->png; close OUT; }