Search code examples
phpimagegd

image GD and png masking


what would be basic code for masking one image with another in GD - one image with black shape and transparent background would be used to crop another image - a photo so that photo is in the shape of black image.

alt text


Solution

  • One way to do it is using phpThumb.

    Basic reference here: http://phpthumb.sourceforge.net/demo/demo/phpThumb.demo.demo.php#x31

    If creating the new image on the fly it would be something as simple as:

    <img src="../phpThumb.php?src=path/to/image/image.jp&fltr[]=mask|path/to/mask/mask.png&f=png" alt="">
    

    To output into a png.

    If doing this after an image upload to create a new image to be stored on the server, first figure out the basics of phpThumb and then set the mask parameters with all the rest:

    For example:

    ...
    require_once('phpThumb/phpthumb.class.php');
    
    //Begin phpThumb work to resize image and create thumbnail
    $uploaddir = $_SERVER['DOCUMENT_ROOT'] . $destination;
    $uploadfile = $uploaddir . $file;
    
    $phpThumb = new phpThumb();
    
    // set data source -- do this first, any settings must be made AFTER this call
    $phpThumb->setSourceFilename($uploadfile);
    
    $phpThumb->setParameter('w', 360); //change to update the picture size
    $phpThumb->setParameter('h', 470); //change to update the picture size
    
    $phpThumb->setParameter('fltr[]', 'mask|path/to/mask/mask.png'); //set mask 
        $phpThumb->setParameter('f', 'png'); //set png output format
    
    $outputdir = $_SERVER['DOCUMENT_ROOT'] . $destination;
    
    $output_filename = $outputdir . "masked" . $file;
    
    $phpThumb->setParameter('config_allow_src_above_docroot', true);
    
    if ($phpThumb->GenerateThumbnail()) { // this line is VERY important, do not remove it!
    
        if ($phpThumb->RenderToFile($output_filename)) {
    
     ...