Zahymaka
Zahymaka

Reputation: 6621

Convert to alpha using PHP GD

I'm trying to achieve something close to what Fireworks does by using the convert to alpha filter (see http://erskinedesign.com/blog/fireworks-tips-convert-alpha/). Is this possible using only the php gd functions?

My code looks like:

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

My idea is to convert to grayscale, measure how 'dark' a pixel is, then convert it to a black alpha, but I seem to be confusing myself.

Upvotes: 0

Views: 387

Answers (1)

Daniel Morales Lira
Daniel Morales Lira

Reputation: 21

Curiously I was looking for the same thing when I found your question. Ended up building this function, I think it works more less the way you want it.

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

Upvotes: 2

Related Questions