Skip to content

Instantly share code, notes, and snippets.

@jelmervdl
Created September 29, 2012 09:21
Show Gist options
  • Save jelmervdl/3803545 to your computer and use it in GitHub Desktop.
Save jelmervdl/3803545 to your computer and use it in GitHub Desktop.
Compare image
<?php
function diff_images($a, $b)
{
$max_x = max(imagesx($a), imagesx($b));
$max_y = max(imagesy($a), imagesy($b));
$diff = imagecreatetruecolor($max_x, $max_y);
for ($x = 0; $x < $max_x; ++$x)
for ($y = 0; $y < $max_y; ++$y)
imagesetpixel($diff, $x, $y,
create_color($diff, diff_color(
imagecolorat($a, $x, $y),
imagecolorat($b, $x, $y))));
return $diff;
}
function create_color($img, $color)
{
list($red, $green, $blue) = $color;
return imagecolorallocate($img, $red, $green, $blue);
}
function diff_color($a, $b)
{
$rgb_a = rgb($a);
$rgb_b = rgb($b);
$diff = array();
for ($i = 0; $i < 3; ++$i)
$diff[$i] = abs($rgb_a[$i] - $rgb_b[$i]);
return $diff;
}
function rgb($color)
{
$r = ($color >> 16) & 0xFF;
$g = ($color >> 8) & 0xFF;
$b = $color & 0xFF;
return array($r, $g, $b);
}
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$img_a = imagecreatefrompng($_FILES['a']['tmp_name']);
$img_b = imagecreatefrompng($_FILES['b']['tmp_name']);
$diff = diff_images($img_a, $img_b);
header('Content-Type: image/png');
imagepng($diff);
}
else
{
echo '<form method="post" enctype="multipart/form-data">';
echo '<input type="file" name="a"> vs <input type="file" name="b">';
echo '<button type="submit">Compare</button>';
echo '</form>';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment