我正在尝试创建一个带有图像的PHP脚本:
I am trying to create a PHP script that takes an image:
i.stack.imgur/eNvlM.png
然后应用PNG图片:
i.stack.imgur/iJr2I.png
作为面具.
最终结果需要保持透明度:
The end result needs to maintain transparency:
i.stack.imgur/u0l0I.png
如果可能的话,我想在GD中执行此操作,那么ImageMagick暂时不是真正的选择.
If at all possible I want to do this in GD, ImageMagick is not really an option right now.
我将如何处理?
phalacee的帖子(在"PHP/GD,如何将一个圆圈从一个图像复制到另一个图像?"中)似乎正确,但我特别需要使用图像作为蒙版,而不是形状
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使用一个图像掩盖另一个图像,包括透明度
发布评论