PHP GD使用一个图像掩盖另一个图像,包括透明度 [英] PHP GD Use one image to mask another image, including transparency

查看:158
本文介绍了PHP GD使用一个图像掩盖另一个图像,包括透明度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个带有图像的PHP脚本:

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


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

然后应用PNG图片:


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

作为面具.

最终结果需要保持透明度:

The end result needs to maintain transparency:


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

如果可能的话,我想在GD中执行此操作,那么ImageMagick暂时不是真正的选择.

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

我将如何处理?

似乎正确,但我特别需要使用图像作为蒙版,而不是形状

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.

推荐答案

马特(Matt)

如果您用黑色背景上的椭圆形白色填充而不是透明背景的黑色填充来创建png,则以下功能可以做到.

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;
}

?>

这篇关于PHP GD使用一个图像掩盖另一个图像,包括透明度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆