dsf323233323332 2012-07-14 10:24
浏览 59
已采纳

PHP GD:我可以填充透明部分吗?

There is an image which has transparent area. (png image) Now, while doing a imagecopy, can we just fill that transparent area?

Imagemagick can do this easily. Is that possible in php gd?

  • 写回答

3条回答 默认 最新

  • dongzhuoxie1244 2012-07-14 10:44
    关注

    A layered approach via imagecopymerge() is one route. The concept is to merge your source image onto a new image, with a pre-set background image, which will show through the source image's transparency once merged.

    //create main image - transparent, with opaque red square in middle
    $img = imagecreate(60, 60);
    $white = imagecolorallocate($img, 255, 255, 255);
    imagecolortransparent($img, $white); //make background transparent
    $red = imagecolorallocate($img, 255, 0, 0);
    imagefilledrectangle($img, imagesx($img) / 4, imagesy($img) / 4, imagesx($img) - (imagesx($img) / 4), imagesy($img) - (imagesy($img) / 4), $red);
    
    //create new image, with pre-filled background, then merge first image across
    $img2 = imagecreate(60, 60);
    $blue = imagecolorallocate($img2, 0, 0, 255);
    imagecopymerge($img2, $img, 0, 0, 0, 0, imagesx($img), imagesy($img), 100);
    
    //output
    imagepng($img2);
    

    So the first image creates a transparent image (the white) with a red square in the middle. The second image is simply a blue fill.Merge the two, and the blue shows through the transparent part of the first image, so our red square now sits on the blue fill. Effectively, we've filled the transparent part.

    Here's the three states in sequence.

             
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?