dounaoji2054 2011-08-26 10:08
浏览 70
已采纳

PHP GD使用一个图像来屏蔽另一个图像,包括透明度

I am trying to create a PHP script that takes an image:

image1
http://i.stack.imgur.com/eNvlM.png

and then applies a PNG image:

mask
http://i.stack.imgur.com/iJr2I.png

as a mask.

The end result needs to maintain transparency:

result
http://i.stack.imgur.com/u0l0I.png

If at all possible I want to do this in GD, ImageMagick is not really an option right now.

How would I go about this?

phalacee's post (in "PHP/GD, how to copy a circle from one image to another?") seems to be along the right lines but I specifically need to use an image as a mask, not a shape.

  • 写回答

6条回答 默认 最新

  • dougekui1518 2011-08-29 11:46
    关注

    Matt,

    If you make your png with the oval white fill on black background instead of black fill with transparent background the following function does it.

    <?php
    // Load source and mask
    $source = imagecreatefrompng( '1.png' );
    $mask = imagecreatefrompng( '2.png' );
    // Apply mask to source
    imagealphamask( $source, $mask );
    // Output
    header( "Content-type: image/png");
    imagepng( $source );
    
    function imagealphamask( &$picture, $mask ) {
        // Get sizes and set up new picture
        $xSize = imagesx( $picture );
        $ySize = imagesy( $picture );
        $newPicture = imagecreatetruecolor( $xSize, $ySize );
        imagesavealpha( $newPicture, true );
        imagefill( $newPicture, 0, 0, imagecolorallocatealpha( $newPicture, 0, 0, 0, 127 ) );
    
        // Resize mask if necessary
        if( $xSize != imagesx( $mask ) || $ySize != imagesy( $mask ) ) {
            $tempPic = imagecreatetruecolor( $xSize, $ySize );
            imagecopyresampled( $tempPic, $mask, 0, 0, 0, 0, $xSize, $ySize, imagesx( $mask ), imagesy( $mask ) );
            imagedestroy( $mask );
            $mask = $tempPic;
        }
    
        // Perform pixel-based alpha map application
        for( $x = 0; $x < $xSize; $x++ ) {
            for( $y = 0; $y < $ySize; $y++ ) {
                $alpha = imagecolorsforindex( $mask, imagecolorat( $mask, $x, $y ) );
                $alpha = 127 - floor( $alpha[ 'red' ] / 2 );
                $color = imagecolorsforindex( $picture, imagecolorat( $picture, $x, $y ) );
                imagesetpixel( $newPicture, $x, $y, imagecolorallocatealpha( $newPicture, $color[ 'red' ], $color[ 'green' ], $color[ 'blue' ], $alpha ) );
            }
        }
    
        // Copy back to original picture
        imagedestroy( $picture );
        $picture = $newPicture;
    }
    
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历