Search code examples
phpimage-resizing

PNG image showing black background on uploading/resizing


I am uploading a image and its resizing, but on PNG, its showing black Background.

Can you please check the code and let me know what is the issue?

$newImageWidth = ceil($width * $scale);
        $newImageHeight = ceil($height * $scale);
        $newImage = imagecreatetruecolor($newImageWidth,$newImageHeight);
        if ($ext == "jpg" || $ext == "jpeg")
        {
            $source = imagecreatefromjpeg($image);
        }
        else
        if ($ext == "png")
        {
            $source = imagecreatefrompng($image);
        }
        else
        {
            $source = imagecreatefromgif($image);
        }

        imagecopyresampled($newImage,$source,0,0,0,0,$newImageWidth,$newImageHeight,$width,$height);
        imagejpeg($newImage,$image,90);
        chmod($image, 0777);
        return $image;

Solution

  • Answer:

    Added this code before imagecopyresampled() function

    $tmp = imagecreatetruecolor($new_width,$new_height);
    imagefilledrectangle($tmp, 0, 0, $new_width, $new_height, imagecolorallocate($tmp, 255, 255, 255));
    

    and its start working as i want....