Combine 2-3 transparent PNG images on top of each other with PHP

后端 未结 5 1607
小蘑菇
小蘑菇 2020-12-04 11:17

I am working on a custom avatar system for a project, but I have never really done much with the image side of PHP. I assume I need to use GD in some way, but I have no ide

5条回答
  •  再見小時候
    2020-12-04 12:13

    Also can be done in this way. Hope this will be useful for future visitors.

    $base = imagecreatefrompng('your base image path');
    //logo is transparent: in this case stackoverflow logo
    $logo = imagecreatefrompng("path for image with transparent background");
    
    //Adjust paramerters according to your image
    imagecopymerge_alpha($base, $logo, 60, 60, 0, 0, 300, 200, 100);
    
    header('Content-Type: image/png');
    imagepng($base);
    
    //@see: http://php.net/manual/en/function.imagecopymerge.php for below function in first comment
    function imagecopymerge_alpha($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $pct){ 
            // creating a cut resource 
            $cut = imagecreatetruecolor($src_w, $src_h); 
    
            // copying relevant section from background to the cut resource 
            imagecopy($cut, $dst_im, 0, 0, $dst_x, $dst_y, $src_w, $src_h); 
    
            // copying relevant section from watermark to the cut resource 
            imagecopy($cut, $src_im, 0, 0, $src_x, $src_y, $src_w, $src_h); 
    
            // insert cut resource to destination image 
            imagecopymerge($dst_im, $cut, $dst_x, $dst_y, 0, 0, $src_w, $src_h, $pct); 
        } 
    

    Working Example: This is background Image
    This is stackoverflow logo.

    This is combined Result.

提交回复
热议问题