Chris
Chris

Reputation: 889

PHP PNG 24 bit clean Transparency

I have been trying to get a PNG to upload with a clean, 24 bit alpha transparency. After doing a lot of research, I have managed to get it sort of working, however the transparency seems to be low quality 8 bit as you can see here in this screenshot:

http://cozomo.com/apple.png

Any help to achieve a clean PNG upload and resize with 24 bit smooth transparency would be much appreciated. My current code is below.

if($extension=="png")
    {
        $uploadedfile = $_FILES['photo']['tmp_name'];
        $src = imagecreatefrompng($uploadedfile);
    }

        $dest_x = 1400; 
        $dest_y = 1200;

        if ($width > $dest_x or $height > $dest_y) { 

                if ($width >= $height) { 
                    $fullSize_x = $dest_x; 
                    $fullSize_y = $height*($fullSize_x/$width); 
                } else { 
                    $fullSize_x = $width*($fullSize_y/$height); 
                    $fullSize_y = $dest_y; 
                } 
        }

        $fullSize=imagecreatetruecolor($fullSize_x,$fullSize_y);

    //TEST
    $black = imagecolorallocate($fullSize, 0, 0, 0);
    imagecolortransparent($fullSize, $black);
    //TEST END

    // OUTPUT NEW IMAGES
    imagecopyresampled($fullSize,$src,0,0,0,0,$fullSize_x,$fullSize_y,$width,$height);

    imagepng($fullSize, "/user/photos/".$filename);

    imagedestroy($fullSize);


  [1]: https://i.sstatic.net/w8VBI.png

Upvotes: 3

Views: 3124

Answers (2)

Chris
Chris

Reputation: 889

Here is the revised code thanks to Musa for anyone having the same issue

function processPNG($pngImage) {
        $black = imagecolorallocate($pngImage, 0, 0, 0);
        imagecolortransparent($pngImage, $black);
        imagealphablending($pngImage, false);
        imagesavealpha($pngImage, true);
    }    


   if($extension=="png")
{
    $uploadedfile = $_FILES['photo']['tmp_name'];
    $src = imagecreatefrompng($uploadedfile);
}

    $dest_x = 1400; 
    $dest_y = 1200;

    if ($width > $dest_x or $height > $dest_y) { 

            if ($width >= $height) { 
                $fullSize_x = $dest_x; 
                $fullSize_y = $height*($fullSize_x/$width); 
            } else { 
                $fullSize_x = $width*($fullSize_y/$height); 
                $fullSize_y = $dest_y; 
            } 
    }

    $fullSize=imagecreatetruecolor($fullSize_x,$fullSize_y);
    if ($extension == "png") processPNG($fullSize);


// OUTPUT NEW IMAGES
imagecopyresampled($fullSize,$src,0,0,0,0,$fullSize_x,$fullSize_y,$width,$height);

imagepng($fullSize, "/user/photos/".$filename);

imagedestroy($fullSize);

Upvotes: 1

Musa
Musa

Reputation: 97727

To save the full alpha channel you'll have to use imagesavealpha, put this before you save the png

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

Upvotes: 5

Related Questions