Skip to content
Advertisement

Resizing PNG image turns black after upload in PHP

I tried creating a thumbnail for every image uploaded. It includes resizing the image to specified ratio and also converting it to .webp extension.

But it turns black after being uploaded. All that I have searched is not working for me, specifically this

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

I also tried saving it into .png using imagepng($resized, $thumbnail_dir, $quality) to see if this affects the problem. But still no luck.

Here is my code for creating thumbnail. I hope you can help me.

// Create thumbnail
public function createThumbnail($image, $new_height, $dir, $quality = 100){
    $image_info = pathinfo($image);
    $ext = $image_info['extension'];
    $filename = $image_info['filename'];

    // Open original image
    if($ext == "jpeg" || $ext == "jpg"){
        $original = imagecreatefromjpeg($image);
    }else if($ext == "png"){
        $original = imagecreatefrompng($image);
    }else if($ext == "webp"){
        $original = imagecreatefromwebp($image);
    }

    // Get image dimensions
    $size = getimagesize($image);
    $original_width = $size[0];
    $original_height = $size[1];

    // Resize image
    if($new_height < $original_height){
        $ratio = $original_width / $original_height;
        $new_width = ceil($ratio * $new_height);
    }else{
        $new_width = $original_width;
        $new_height = $original_height;
    }
    
    $resized = imagecreatetruecolor($new_width, $new_height);

    $background = imagecolorallocate($resized, 255, 255, 255);
    imagecolortransparent($resized, $background);
    imagealphablending($resized, false);
    imagesavealpha($resized, true);
    
    imagecopyresampled(
        $resized, $original,
        0,0,0,0,
        $new_width, $new_height,
        $original_width, $original_height
    );

    // Save thumbnail
    $thumbnail_dir = $dir."thumb/".$filename.".webp";
    imagewebp($resized, $thumbnail_dir, $quality);

    imagedestroy($original);
    imagedestroy($resized);

    return $thumbnail_dir;
}

Advertisement

Answer

You can try this. It should be working.

I am using the following two libraries to fix the issue.

https://github.com/rosell-dk/webp-convert

http://image.intervention.io/getting_started/installation

    use InterventionImageImageManager;
    use WebPConvertWebPConvert;

    function create_thumbnail_webp_image(){
    $msg = null;
    $target_dir = $_SERVER['DOCUMENT_ROOT'] . "/converted_images/";
    $target_file = $target_dir . basename($_FILES["upload_file_name"]["name"]);
    $unique_file_name = md5($_FILES["upload_file_name"]["name"] . time());
    $uploadOk = 1;
    $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
    $image_info = pathinfo($target_file);
    $target_file = $target_dir . $unique_file_name . '.' . $image_info['extension'];

    // Check if image file is a actual image or fake image
    if (isset($_POST["submit"])) {
        $check = getimagesize($_FILES["upload_file_name"]["tmp_name"]);
        if ($check !== false) {
            $uploadOk = 1;
        } else {
            $msg .= " File is not an image.";
            $uploadOk = 0;
        }
    }

     // Check if file already exists
    if (file_exists($target_file)) {
        $msg .= " File already exists.";
        $uploadOk = 0;
    }

    // Check file size
    if ($_FILES["upload_file_name"]["size"] > 500000) {
        $msg .= " Your file is too large.";
        $uploadOk = 0;
    }

    // Allow certain file formats
    if ($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
        && $imageFileType != "gif" && $imageFileType != "webp") {
        $msg .= " Only JPG, JPEG, PNG, GIF, WEBP files are allowed.";
        $uploadOk = 0;
    }

    // Check if $uploadOk is set to 0 by an error
    if ($uploadOk == 0) {
        $msg .= " Sorry, your file was not uploaded.";
        redirect('new_banner_image', $image_id, $msg, 'warn');
    // if everything is ok, try to upload file
    } else {
        if (move_uploaded_file($_FILES["upload_file_name"]["tmp_name"], $target_file)) {
            if ($imageFileType != 'webp') {
                // Save the webp image
                WebPConvert::convert($target_file, $image_info['dirname'] . '/' . $unique_file_name . '.webp');
            }

            // use third party image library to fetch the image
            $manager = new ImageManager(array('driver' => 'gd'));

            // open an image file
            $img = $manager->make($target_file);

            // now you are able to resize the instance
            $img->resize(320, 240);


            // finally we save the image as a new file
            $img->save($image_info['dirname'] . '/' . $unique_file_name . '.png');


            $msg .= " The file " . basename($_FILES["upload_file_name"]["name"]) . " has been uploaded.";
        } else {
            $msg .= "Sorry, there was an error uploading your file.";
        }
    }
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement