合并两个PNG图像在php



我试图在php合并我的两个图像。一张图片是从我的系统上传的,另一张是我用透明背景创建的。这是我的代码。我的代码只是显示一个非图像图标。我不明白我错在哪里。

    <?php
    //Set the Content Type
    header("Content-type: image/png");
    #dispaly the image
    $file=$_GET['file'];
    // echo file_get_contents($file);
    $im = imagecreatetruecolor(250, 200);
    $black = imagecolorallocate($im, 255, 255, 255);
    $blue = imagecolorallocate($im, 0, 0, 255);
    imagecolortransparent($im, $black);
    //text to draw
    $text="hello world";
    //font path
    $font = '/usr/share/fonts/truetype/droid/DroidSans.ttf';
    // Add the text
    imagettftext($im, 15, 0, 50, 50, $blue, $font, $text);
    $dest=imagecreatefrompng($file);
    $src=imagecreatefrompng($im);
    imagealphablending($dest, false);
    imagesavealpha($dest, true);
    imagecopymerge($dest, $src, 10, 10, 0, 0, 100, 250, 200);
    imagepng($dest);
    imagedestroy($dest);
    imagedestroy($src);
    ?>

使用$im而不是$src -正如Sayed指出的那样,imagecreatefromng接受文件名(字符串)作为参数-而不是GD资源。如果$im已经包含了可供使用的GD资源,为什么要设置$src ?

imagettftext有一个重要的部分。如果GD无法在给定路径中找到字体,我可以重现空图标的效果。检查您的位置,权限和字母大小写。此外,如果您决定将.ttf文件直接复制到脚本位置,请参考imagettftext()文档,因为"。ttf"扩展名有重要的警告。

同样,要创建完全透明的图像,使用:(由George Edison编写,PHP doc for imagefill

)
    $im = imagecreatetruecolor(317, 196);
    $transparent =  imagecolorallocatealpha($im, 0, 0, 0, 127);
    imagefill($im, 0, 0, $transparent);
    imagesavealpha($im, TRUE);

另外,从PHP文档的imagecopymerge()由Sina Salek: imagecopymerge_alpha函数提供真正的透明度在imagecopymerge()

所以,我的解决方案:

    <?php
    //Set the Content Type
    header("Content-type: image/png");
    #dispaly the image
    $file='test.png';
    $im = imagecreatetruecolor(317, 196);
    $transparent =  imagecolorallocatealpha($im, 0, 0, 0, 127);
    imagefill($im, 0, 0, $transparent);
    imagesavealpha($im, TRUE);
    $blue = imagecolorallocatealpha($im, 0, 0, 255, 0);
    //text to draw
    $text="hello world";
    putenv('GDFONTPATH=' . realpath('.'));
    $font = 'lucida';
    imagettftext($im, 20, 0, 10, 50, $blue, $font, $text);
    $dest=imagecreatefrompng($file);
    imagealphablending($dest, false);
    imagesavealpha($dest, true);
    imagecopymerge_alpha($dest, $im, 10, 10, 0, 0, 200, 180, 100);
    imagepng($dest);
    imagedestroy($dest);
    imagedestroy($im);
    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);
    }
    ?>

您应该使用imagecopymerge()函数。

查找链接

http://php.net/manual/en/function.imagecopymerge.php

最新更新