Search code examples
phpimagepngtransparencygd

PHP GD Transparent PNG black bars issue


I'm working on a PHP script that reduce the image file size and it works perfectly fine with JPEG images. However, when uploading a PNG image some weird black bars appear in the resulted image.

Here's an example:

Original image: https://i.sstatic.net/7epzm.jpg

Resulted image: https://i.sstatic.net/7qN6c.jpg

Here's the function call:

compress_image($_FILES["pic"]["tmp_name"], $folder_path . "/" . $pic_new_name, 50);

Here's the function code:

//function for compressing and storing image
function compress_image($source_url, $destination_url, $quality) {
    $info = getimagesize($source_url);
    if ($info['mime'] == 'image/jpeg') 
    $image = imagecreatefromjpeg($source_url);
    elseif ($info['mime'] == 'image/gif') 
    $image = imagecreatefromgif($source_url);
    elseif ($info['mime'] == 'image/png') 
    $image = imagecreatefrompng($source_url);


    imagejpeg($image, $destination_url, $quality);

    return;
} ?>

Is there's any solution or a workaround for this issue?


Solution

  • Hmmm, i'm surprised that only 8 people viewed the post after almost 5 hours. Anyway, I have solved it myself :D

    I hope it will benefit others.

    This is the complete function that will compress & process PNG images correctly and convert them to JPEG with white background:

    //function for compressing and storing image
    function compress_image($source_url, $destination_url, $quality) {
        $info = getimagesize($source_url);
    
    $w = $info[0];
    $h = $info[1];
    
    if ($info['mime'] == 'image/jpeg') {
    $image = imagecreatefromjpeg($source_url);
    imagejpeg($image, $destination_url, $quality);
    }
    
    
    
    elseif ($info['mime'] == 'image/gif') {
    $image = imagecreatefromgif($source_url);
    imagejpeg($image, $destination_url, $quality);
    }
    
    elseif ($info['mime'] == 'image/png') {
    $image = imagecreatefrompng($source_url);
    
    $image_p = imagecreatetruecolor($w, $h);
    $white = imagecolorallocate($image_p, 0xFF, 0xFF, 0xFF);
    imagealphablending($image_p, false);
    ImageSaveAlpha($image_p, true);
    ImageFill($image_p, 0, 0, $white);
    imagealphablending($image_p, true);
    imagecopyresampled($image_p, $image, 0, 0, 0, 0, $w, $h, $w, $h);
    imagejpeg($image_p, $destination_url, $quality);
    
    }
    
    
    return;
    

    Result: https://i.sstatic.net/63XA4.jpg