phpimage-processingimage-comparison

PHP image comparison


img_1 is created by PHP and img_2 is saved on server. I'm trying to compare those to images to see if they're different, I tried this but it doesn't work.

$script_img = imagecreatetruecolor(2390, 2400);
$web_img = imagecreatefrompng("URL_TO_IMG");

if ($script_img==$web_img ) {
    echo "SAME";
}
else{
    echo "DIFFERENT";
}

Next example works but when I call imagepng PHP creates image in browser or weird letters (if headers isn't set to image/png) and I don't want that.

$script_img = imagecreatetruecolor(2390, 2400);
$web_img = imagecreatefrompng("URL_TO_IMG");
$rendered = imagepng($web_img);

if ($script_img==$rendered ) {
    echo "SAME";
}
else{
    echo "DIFFERENT";
}

I also tried file_get_contents($script_img) == file_get_contents("URL_TO_IMG") but it doesn't work.

Using md5(file_get_contents(imagecreatetruecolor(2390, 2400))) == md5(file_get_contents(imagecreatefrompng("URL_TO_IMG"))) works but I doubt that is the best/correct way to compare 2 images.


What is the best/correct way to compare images in PHP?


Solution

  • Why don't you try comparing MD5 Hash of the two images.

      $md5LocalImg = md5(file_get_contents($script_img));
      $md5WebImg   = md5(file_get_contents($web_img));
      if ( $md5LocalImg == $md5WebImg ){
         echo("SAME");
      }
      else{
        echo("DIFFERENT");
      }