Search code examples
phptransparencygd2imagecreatefrompng

How to allow upload transparent gif or png with php


I have this function below to allow me to resize my uploaded image,

function resize_image($image,$width,$height,$scale) 
{
    list($imagewidth, $imageheight, $imageType) = getimagesize($image);
    $imageType = image_type_to_mime_type($imageType);
    $newImageWidth = ceil($width * $scale);
    $newImageHeight = ceil($height * $scale);
    $newImage = imagecreatetruecolor($newImageWidth,$newImageHeight);

    switch($imageType) 
    {
        case "image/gif":
            $source = imagecreatefromgif($image); 
            break;
        case "image/pjpeg":
        case "image/jpeg":
        case "image/jpg":
            $source = imagecreatefromjpeg($image); 
            break;
        case "image/png":
        case "image/x-png":
            $source = imagecreatefrompng($image); 
            break;
    }

    imagecopyresampled($newImage,$source,0,0,0,0,$newImageWidth,$newImageHeight,$width,$height);

    switch($imageType) 
    {
        case "image/gif":
            imagegif($newImage,$image); 
            break;
        case "image/pjpeg":
        case "image/jpeg":
        case "image/jpg":
            imagejpeg($newImage,$image,90); 
            break;
        case "image/png":
        case "image/x-png":
            imagepng($newImage,$image);  
            break;
    }

    chmod($image, 0777);
    return $image;
}

But this function has a problem which is that it cannot create transparency when I have a png or a gif with a transparent background.

How can I fix this function to allow transparency with php?


Solution

  • Here is my answer,

    # This is the resizing/resampling/transparency-preserving magic
        if ( ($imageType == "image/gif") || ($imageType == "image/png") ) 
        {
            $transindex = imagecolortransparent($source);
    
            if($transindex >= 0) 
            {
                $transcol = imagecolorsforindex($source, $transindex);
                $transindex = imagecolorallocatealpha($newImage, $transcol['red'], $transcol['green'], $transcol['blue'], 127);
                imagefill($newImage, 0, 0, $transindex);
                imagecolortransparent($newImage, $transindex);
            }
    
            elseif ($imageType == "image/png" || $imageType == "image/x-png") 
            {
                imagealphablending($newImage, false);
                $color = imagecolorallocatealpha($newImage, 0, 0, 0, 127);
                imagefill($newImage, 0, 0, $color);
                imagesavealpha($newImage, true);
            }
        }
    

    And Work Totally Fine