简体   繁体   English

在 PHP 中上传后调整 PNG 图片变黑

[英]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.它包括将图像大小调整为指定比例,并将其转换为.webp扩展名。

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.我还尝试使用imagepng($resized, $thumbnail_dir, $quality)将其保存为.png以查看这是否会影响问题。 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;
}

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 https://github.com/rosell-dk/webp-convert

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

    use Intervention\Image\ImageManager;
    use WebPConvert\WebPConvert;

    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.";
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM