PHP PNG 24位清洁透明度

时间:2012-06-21 21:22:23

标签: php png transparency

我一直在尝试使用干净的24位alpha透明度上传PNG。经过大量的研究,我已经设法让它有点工作,但透明度似乎是低质量8位,你可以在这个截图中看到:

http://cozomo.com/apple.png

任何有助于实现干净的PNG上传和24位平滑透明度调整的帮助都将非常受欢迎。我目前的代码如下。

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]: http://i.stack.imgur.com/w8VBI.png

2 个答案:

答案 0 :(得分:5)

要保存完整的Alpha通道,您必须使用imagesavealpha,请在保存png之前将其设置为

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

答案 1 :(得分:1)

以下是修改后的代码,感谢Musa对任何有相同问题的人

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