Image Comparison Function in PHP with GD Library
March 24, 2011| Tweet |
Download Original
<?php /** * Image Comparing Function (C)2011 Robert Lerner, All Rights Reserved * $image1 STRING/RESOURCE Filepath and name to PNG or passed image resource handle * $image2 STRING/RESOURCE Filepath and name to PNG or passed image resource handle * $RTolerance INTEGER (0-/+255) Red Integer Color Deviation before channel flag thrown * $GTolerance INTEGER (0-/+255) Green Integer Color Deviation before channel flag thrown * $BTolerance INTEGER (0-/+255) Blue Integer Color Deviation before channel flag thrown * $WarningTolerance INTEGER (0-100) Percentage of channel differences before warning returned * $ErrorTolerance INTEGER (0-100) Percentage of channel difference before error returned */ function imageCompare($image1, $image2, $RTolerance=0, $GTolerance=0, $BTolerance=0, $WarningTolerance=1, $ErrorTolerance=5) { $im = $image1; else $im2 = $image2; else $OutOfSpec = 0; //By columns { { $r1 = ($rgb >> 16) & 0xFF; $g1 = ($rgb >> 8) & 0xFF; $b1 = $rgb & 0xFF; $r2 = ($rgb >> 16) & 0xFF; $g2 = ($rgb >> 8) & 0xFF; $b2 = $rgb & 0xFF; if (!($r1>=$r2-$RTolerance && $r1<=$r2+$RTolerance)) $OutOfSpec++; if (!($g1>=$g2-$GTolerance && $g1<=$g2+$GTolerance)) $OutOfSpec++; if (!($b1>=$b2-$BTolerance && $b1<=$b2+$BTolerance)) $OutOfSpec++; } } $RET['PixelsByColors'] = $TotalPixelsWithColors; $RET['PixelsOutOfSpec'] = $OutOfSpec; if ($OutOfSpec!=0 && $TotalPixelsWithColors!=0) { $PercentOut = ($OutOfSpec/$TotalPixelsWithColors)*100; $RET['PercentDifference']=$PercentOut; if ($PercentOut>=$WarningTolerance) //difference triggers WARNINGTOLERANCE% $RET['WarningLevel']=TRUE; if ($PercentOut>=$ErrorTolerance) //difference triggers ERRORTOLERANCE% $RET['ErrorLevel']=TRUE; } RETURN $RET; }
Use:
$diff = imageCompare("c:/building.png","c:/building2.png",5,5,5,1,5);
echo "<pre>";
print_r($diff);
Using these images:
Returns:
Array
(
[PixelsByColors] => 19608
[PixelsOutOfSpec] => 224
[PercentDifference] => 1.1423908608731
[WarningLevel] => 1
)
Interpretation of Results:
PixelsByColors = Pixel Count * 3 (for R, G, and B)
PixelsOutOfSpec = (If a pixel varies outside of xTolerance, for each red, green, and blue. Where x = R/G/B) If any channel exceeds the threshhold, this number is incremented.
PercentDifference = PixelsOutOfSpec/PixelsByColors*100
WarningLevel = TRUE (or 1) if level exceeds prescribed level
ErrorLevel = TRUE (or 1) if level exceeds prescribed level
Comment
| Posted: Saturday, June 18, 2011 at 1:53:18 AM |
| By: Mangesh |
| thank you for the code.. I wish to grab the pixel location where the difference is.. how do i do that? |
| Posted: Friday, May 4, 2012 at 8:00:29 AM |
| By: R. Mattu |
| Great! It works for me. Thanks for posting the script. |

Facebook
LinkedIn