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条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!