使用PHP GD转换为alpha

时间:2013-05-02 23:11:36

标签: php transparency gd

我正在尝试通过使用转换为alpha过滤器来实现与Fireworks相近的功能(请参阅http://erskinedesign.com/blog/fireworks-tips-convert-alpha/)。这只能使用php gd函数吗?

我的代码如下:

$img = imagecreatefromstring(file_get_contents('...'));

imagealphablending($img, true);
$transparentcolour = imagecolorallocate($img, 255,255,255);
imagecolortransparent($img, $transparentcolour);
imagefilter($img, IMG_FILTER_GRAYSCALE);

$w = imagesx($img);
$h = imagesy($img);

for ($x=0; $x<$w; $x++)
{
    for ($y=0; $y<$h; $y++)
    {
        $color = imagecolorsforindex($img, imagecolorat($img, $x, $y));

        if ($color['alpha'] == 0)
            continue;
    }
}
imagepng($img);
exit;

我的想法是转换为灰度,测量一个像素的“暗”,然后将其转换为黑色alpha,但我似乎让自己感到困惑。

1 个答案:

答案 0 :(得分:2)

奇怪的是,当我找到你的问题时,我正在寻找同样的事情。最后建立了这个功能,我认为它的工作方式更少。

function n2_image_make_alpha( $im , $percentage )
{
    imagefilter( $im , IMG_FILTER_GRAYSCALE );

    $width = imagesx( $im );
    $height = imagesy( $im );

    imagealphablending( $im , false );
    imagesavealpha( $im , true );

    $newim = imagecreatetruecolor( $width , $height );
    imagealphablending( $newim , false );
    imagesavealpha( $newim , true );


    //Loop through pixels
    for ( $x = 0 ; $x < $width ; $x++ )
    {
        for ( $y = 0 ; $y < $height ; $y++ )
        {
            //Get the color of the pixel
            $color = imagecolorat( $im , $x , $y );
            //Get the rgba of the color
            $rgba = imagecolorsforindex( $im , $color );
            $alpha = $rgba['alpha'];
            if ( $alpha < 127 )
            {
                $base_alpha = 127 - $alpha; //100% of the difference between completely transparent and the current alpha
                $percentage_to_increase_alpha = intVal( $percentage * $base_alpha / 100 );
                $alpha = $alpha + $percentage_to_increase_alpha;
            }
            $new_color = imagecolorallocatealpha ( $newim , $rgba['red'] , $rgba['green'] , $rgba['blue'] , $alpha );
            imagesetpixel ( $newim , $x , $y , $new_color );
        }
    }
    return $newim;
}