一种获得类似效果的不同方法是将PNG文件粘贴到具有唯一背景颜色的新图像上,以暂时去除透明度,并将PNG图像的透明颜色设置为黑色圆形颜色。然后,当您将其放置在JPEG图像上时,将新的透明颜色设置为掩码的颜色。
$png = imagecreatefrompng( 'mask.png' );
$width = imagesx( $png );
$height = imagesy( $png );
$mask = imagecreatetruecolor( $width, $height );
$magenta = imagecolorallocate( $mask, 255, 0, 255 );
imagefill( $mask, 0, 0, $magenta );
imagecopyresampled( $mask, $png, 0, 0, 0, 0, $width, $height, $width, $height );
imagedestroy( $png );
$black = imagecolorallocate( $mask, 0, 0, 0 );
imagecolortransparent( $mask, $black );
$jpg = imagecreatefromjpeg( 'image.jpg' );
$j_width = imagesx( $jpg );
$j_height = imagesx( $jpg );
imagealphablending( $jpg, true );
imagecopyresampled( $jpg, $mask, 0, 0, 0, 0, $j_width, $j_height, $width, $height );
imagedestroy( $mask );
$magenta = imagecolorallocate( $jpg, 255, 0, 255 );
imagecolortransparent( $jpg, $magenta );
imagepng( $jpg );
如果重新采样或半透明像素让您感到沮丧,您可以禁用混合并在 $mask 图像上绘制一个透明的形状,而不是使用 png 作为遮罩。
$jpg = imagecreatefromjpeg( 'image.jpg' );
$width = imagesx( $jpg );
$height = imagesx( $jpg );
$mask = imagecreatetruecolor( $width, $height );
$magenta = imagecolorallocate( $mask, 255, 0, 255 );
imagefill( $mask, 0, 0, $magenta );
$transparent = imagecolorallocatealpha( $mask, 255, 255, 255, 127 );
imagealphablending( $mask, false );
imagefilledellipse( $mask, round( $width / 2 ), round( $height / 2 ), $width, $height, $transparent );
imagealphablending( $jpg, true );
imagecopyresampled( $jpg, $mask, 0, 0, 0, 0, $width, $height, $width, $height );
imagedestroy( $mask );
$magenta = imagecolorallocate( $jpg, 255, 0, 255 );
imagecolortransparent( $jpg, $magenta );
imagepng( $jpg );
注意:上述代码未经测试,但应该能够满足您的需求。
$alpha = 127 - floor( $alpha[ 'red' ] / 2 ); $color = imagecolorsforindex( $picture, imagecolorat( $picture, $x, $y ) );
这两行代码替换为$color = imagecolorsforindex( $picture, imagecolorat( $picture, $x, $y ) ); $alpha = 127 - floor((127-$color['alpha']) * ($alpha[ 'red' ]/255));
以防止丢失源图像的 alpha 通道。 - Samired
索引而不是green
或blue
索引吗?$alpha = 127 - floor( $alpha[ 'red' ] / 2 );
- tirenweb