phpimagemagickimagick

Create inset shadow with PHP imagick


I want to add an inset shadow to image with PHP Imagick extension.

I'm using ImageMagick 7.1.0-17 Q16-HDRI x64 2021-12-04.

Imagick::shadowImage function works like outline CSS box-shadow property:

box-shadow: 3px 3px 6px 2px rgba(0,0,0,0.28);

But my goal is create something similar to:

box-shadow: inset 3px 3px 6px 2px rgba(0,0,0,0.28);

Thanks to hint in the question How to add inner shadow to image using imagemagick?

I have created next snippet:

<?php

$path  = realpath('oOU3n.jpg');
$image = new \Imagick($path);
$sizes = $image->getImageGeometry();

$w = $sizes['width'];
$h = $sizes['height'];

$whitePixel = new \ImagickPixel('white');
$whiteImage = new \Imagick();

$whiteImage->newImage($w, $h, $whitePixel);
$whiteImage->setImageBackgroundColor('black');
//$whiteImage->colorizeImage('red', 100, true);

//https://www.php.net/manual/en/imagick.constants.php#imagick.constants.virtualpixelmethod-undefined
$m1 = \Imagick::VIRTUALPIXELMETHOD_BACKGROUND;
$m2 = \Imagick::VIRTUALPIXELMETHOD_BLACK;

$whiteImage->setImageVirtualPixelMethod($m1);
$whiteImage->blurImage(0, 10);

$whiteImage->compositeImage($image, \Imagick::COMPOSITE_MULTIPLY, 0, 0);
$whiteImage->setImageFormat('png');

header('Content-Type: image/png');
echo $whiteImage->getImageBlob();

But shadow exists from all sides, not a top & left. Is it possible to achieve correct results?

Origin image:

enter image description here

Generated image:

enter image description here

EDIT: Thanks @fmw42 for your help.

If anyone else is looking for the same function, correct snippet looks like this:

$m = \Imagick::VIRTUALPIXELMETHOD_BLACK;

$whiteImage->setImageVirtualPixelMethod($m);

//$whiteImage->blurImage(0, 10);
$kernel1 = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_COMET, "0,10");
$kernel2 = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_COMET, "0,10+90");
$iterations = 1;

$whiteImage->morphology(\Imagick::MORPHOLOGY_CONVOLVE, $iterations, $kernel1);
$whiteImage->morphology(\Imagick::MORPHOLOGY_CONVOLVE, $iterations, $kernel2);

Solution

  • Sorry, I do not do iMagick, but in Imagemagick you can use the comet blur (see https://imagemagick.org/Usage/convolve/#comet) as follows:

    enter image description here

    convert barn.jpg \
    \( +clone -fill white -colorize 100 -virtual-pixel black -morphology convolve comet:0x10 \
    -morphology convolve comet:0x10+90 \) \
    -compose multiply -composite barn_inner.jpg
    

    enter image description here