Illusion Illusion - 1 month ago 9
PHP Question

PHP PNG Image Upload losing transparency

I am trying to upload image using the php GD functions and I have found many solutions to properly upload the image without loosing transparency. I have tried to use most of them but due to some reason I failed every time. My code is

switch($ext) {
case 'PNG':
case 'png':
$oImage = imagecreatefrompng($sFileName);
break;

case 'GIF':
case 'gif':
$oImage = imagecreatefromgif($sFileName);
break;

default:
$oImage = imagecreatefromjpeg($sFileName);
break;
}

$kW = $aSize[0] / $params['size']['width'];
$kH = $aSize[1] / $params['size']['height'];
if($kW > $kH) {
$w1 = round($params['size']['width'] * $kH);
$h1 = $aSize[1];
}
else {
$w1 = $aSize[0];
$h1 = round($params['size']['height'] * $kW);
}

$oBuffer = ImageCreateTrueColor($params['size']['width'], $params['size']['height']);
ImageCopyResampled($oBuffer, $oImage, 0, 0, 0, 0, $params['size']['width'], $params['size']['height'], $w1, $h1);

if(file_exists($sFileName)) {
unlink($sFileName);
}

imagejpeg($oBuffer, $sFileName);
// Also tried
imagepng($oBuffer, $sFileName);
return $sFilename;


Can anyone help me point out my mistake please..

Answer

Here is the solution I think will do the trick for you.

$oBuffer = ImageCreateTrueColor($params['size']['width'], $params['size']['height']);
        imagealphablending($oBuffer, false);
        imagesavealpha($oBuffer, true);  
        imagealphablending($oImage, true);
        imagecopyresampled($oBuffer, $oImage, 0, 0, 0, 0, $params['size']['width'],     $params['size']['height'], $w1, $h1); 
        if(file_exists($sFileName)) {
            unlink($sFileName);
        }
        imagepng($oBuffer, $sFileName);
        chmod($sFileName, 0777);
        return $sFileName;

Notice that I have used imagealphablending two times and also the point which DMSJax pointed out. Hope that helps. Cheers.

Comments