How to add a gradient into transparency at the border of an image with PHP Imagic

38 Views Asked by At

I am constructing a graphine, used in place of any user's photograph that does not have such. I have constructed it by using a login and transforming it into geometrical shapes on white background. All is working fine, but i would like to have gradual gradient into transparent at the border of the image.

Currently the generated image looks like

already existing image

I would like to make it be something like

desired image

The way i have produced the desired image in Gimp is:

  1. Add a layer mask with full transparency
  2. Select entire image
  3. Feather selection by 30 px
  4. Fill the layer mask with white within the selection

Can i perform similar transformations in PHP with Image Magic?

2

There are 2 best solutions below

1
Oyinlade Demola On

Yes i believe so below is a sample syntax to do so Please not that the code is not tested when I get in front of my machine I can test and review the code.

<?php


$imagick = new \Imagick('OxMui.png');


$width = $imagick->getImageWidth();
$height = $imagick->getImageHeight();
echo $width;
// Create a gradient mask
$gradient = new \Imagick();
$gradient->newPseudoImage($width, $height, 'gradient:rgba(255,255,255,0)-rgba(255,255,255,1)');

// Apply the gradient mask to the original image
$imagick->compositeImage($gradient, \Imagick::COMPOSITE_COPYOPACITY, 0, 0);

$imagick->setImageFormat('png');
$imagick->writeImage('output.png');
$imagick->destroy();
0
v010dya On

I have managed to alter the approach of Oyinlade Demola and came up with the different way to create the mask, that suited my purpose:

$mask = new Imagick();
$mask->newPseudoImage(200, 200, 'canvas:transparent');
$draw = new \ImagickDraw();
$draw->setStrokeColor( new ImagickPixel( 'black' ) );
$draw->setFillColor( new ImagickPixel( 'black' ) );
$draw->roundRectangle(10, 10, 200-15, 200-15, 30, 30);
$mask->drawImage( $draw );
$mask->blurImage(30, 15);

$canvas->compositeImage($mask, \Imagick::COMPOSITE_COPYOPACITY, 0, 0);

The result that i get isenter image description here

I wasn't aware that COMPOSITE_COPYOPACITY exists, and that was a large part of this question, but using gradient is not suitable for the mask.