Search code examples
phpimagemagickimagick

Remove background after comparing two images with Imagick


i'm new using imagick with php and i have a problem: I'm comparing two images with the compareImages() function. I'm using the same code as in the documentation page:

<?php

$image1 = new imagick("image1.png");
$image2 = new imagick("image2.png");

$result = $image1->compareImages($image2, Imagick::METRIC_MEANSQUAREERROR);
$result[0]->setImageFormat("png");

header("Content-Type: image/png");
echo $result[0];

?>

This code is working right, but the result image has a background with the original image with a bit of opacity.

I've been searching and I found the result that I want but with imagemagick commands: http://www.imagemagick.org/Usage/compare/

My current result is like the image of the first command ("compare bag_frame1.gif bag_frame2.gif compare.gif") and I want a result like the shown in this command:

 compare bag_frame1.gif bag_frame2.gif \
      -compose Src compare_src.gif

Is there any way of doing this with the compareImages() function of imagick?

Thanks


Solution

  • You'll need to use Imagick::SetOption before reading the first image.

    <?php
    $image1 = new imagick(); // Init empty object
    $image2 = new imagick("image2.png");
    // Set Lowlight (resulting background) to transparent, not "original image with a bit of opacity"
    $image1->setOption('lowlight-color','transparent');
    // Switch the default compose operator to Src, like in example
    $image1->setOption('compose', 'Src');
    // Now read image
    $image1->readImage("image1.png");
    // Result will not have a background
    $result = $image1->compareImages($image2, Imagick::METRIC_MEANSQUAREERROR);