代码之家  ›  专栏  ›  技术社区  ›  Razvan Zamfir

为什么这种PHP图像转换方法会创建完全透明的图像?

  •  0
  • Razvan Zamfir  · 技术社区  · 5 年前

    我正在使用下面的方法将图像批量转换为 .webp 格式(借用自 here ):

    public function convertToWebp($file, $compression_quality = 80) {
        // check if file exists
        if (!file_exists($file)) {
            return false;
        }
    
        // If output file already exists return path
        $output_file = $file . '.webp';
        if (file_exists($output_file)) {
            return $output_file;
        }
    
        $file_type = strtolower(pathinfo($file, PATHINFO_EXTENSION));
    
    
        if (function_exists('imagewebp')) {
    
            switch ($file_type) {
                case 'jpeg':
                case 'jpg':
                    $image = imagecreatefromjpeg($file);
                    break;
    
                case 'png':
                    $image = imagecreatefrompng($file);
                    imagepalettetotruecolor($image);
                    imagealphablending($image, true);
                    imagesavealpha($image, true);
                    break;
    
                case 'gif':
                    $image = imagecreatefromgif($file);
                    break;
                default:
                    return false;
            }
    
            // Save the image
            $result = imagewebp($image, $output_file, $compression_quality);
            if (false === $result) {
                return false;
            }
    
            // Free up memory
            imagedestroy($image);
    
            return $output_file;
        } elseif (class_exists('Imagick')) {
            $image = new Imagick();
            $image->readImage($file);
    
            if ($file_type === 'png') {
                $image->setImageFormat('webp');
                $image->setImageCompressionQuality($compression_quality);
                $image->setOption('webp:lossless', 'true');
            }
    
            $image->writeImage($output_file);
            return $output_file;
        }
    
        return false;
    }
    

    在视图文件中:

    foreach ($images as $image) {
      <img class="img-responsive" src="<?= convertToWebp($image);?>"/>
    }
    

    问题

    虽然大多数图像已成功转换,但有些图像是完全透明的。

    少了什么?

    如果Imagick库不支持 .韦伯 什么是好的解决方法?

    0 回复  |  直到 5 年前
    推荐文章