Search code examples
phpimage-processinggdalpha-transparency

PHP : How to create a shadow to an image using an alpha mask


I have a PNG image with an alpha mask. I want to generate a shadow for this image, that would use the alpha mask.

a picture is worth thousand words http://www.brunet.fr/alpha.jpg

I suppose I would need to :

  1. get the alpha mask from the first image
  2. fill it with the appropriate color, and blur it
  3. create a new blank white image
  4. compose it with the shadow first, and the first image

But I can't found anywhere some tips, especially for the first part.

Edit : i found a begining of answer here I try it and let you know.

Thanks


Solution

  • At first , you need install the php ext named : Imagick

    <?php 
    /* Read the image into the object */ 
    $im = new Imagick( 'a.png' ); 
    $im->setImageFormat("png"); 
    
    /* Make the image a little smaller, maintain aspect ratio */ 
    $im->thumbnailImage( 200, null ); 
    
    /* Clone the current object */ 
    $shadow = $im->clone(); 
    
    /* Set image background color to black 
            (this is the color of the shadow) */ 
    $shadow->setImageBackgroundColor( new ImagickPixel( 'black' ) ); 
    
    /* Create the shadow */ 
    $shadow->shadowImage( 80, 3, 5, 5 ); 
    
    /* Imagick::shadowImage only creates the shadow. 
            That is why the original image is composited over it */ 
    $shadow->compositeImage( $im, Imagick::COMPOSITE_OVER, 0, 0 ); 
    
    /* Display the image */ 
    header( "Content-Type: image/png" ); 
    echo $shadow;