【问题标题】:How can I convert all images to jpg?如何将所有图像转换为 jpg?
【发布时间】:2013-01-11 01:09:42
【问题描述】:

我有脚本:

<?php

include('db.php');
session_start();
$session_id = '1'; // User session id
$path = "uploads/";

$valid_formats = array("jpg", "png", "gif", "bmp", "jpeg");
if (isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") {
    $name = $_FILES['photoimg']['name'];
    $size = $_FILES['photoimg']['size'];
    if (strlen($name)) {
        list($txt, $ext) = explode(".", $name);
        if (in_array($ext, $valid_formats)) {
            if ($size < (1024 * 1024)) { // Image size max 1 MB
                $actual_image_name = time() . $session_id . "." . $ext;
                $tmp = $_FILES['photoimg']['tmp_name'];
                if (move_uploaded_file($tmp, $path . $actual_image_name)) {
                    mysql_query("UPDATE users SET profile_image='$actual_image_name' WHERE uid='$session_id'");
                    echo "<img src='uploads/" . $actual_image_name . "' class='preview'>";
                } else {
                    echo "failed";
                }
            } else {
                echo "Image file size max 1 MB";
            }
        } else {
            echo "Invalid file format..";
        }
    } else {
        echo "Please select image..!";
    }
    exit;
}

?>

是否可以将所有图像(png、gif 等)转换为 100% 质量的 jpg?如果是,如何?我想允许上传 png 和 gif,但这个脚本应该将此文件转换为 jpg。 PHP有可能吗?

【问题讨论】:

标签: php image-processing


【解决方案1】:

Davide Berra 的回答很棒,所以我稍微改进了文件类型检测,使用 exif_imagetype() 而不是依赖文件扩展名:

/**
*   Auxiliar function to convert images to JPG
*/
function convertImage($originalImage, $outputImage, $quality) {

    switch (exif_imagetype($originalImage)) {
        case IMAGETYPE_PNG:
            $imageTmp=imagecreatefrompng($originalImage);
            break;
        case IMAGETYPE_JPEG:
            $imageTmp=imagecreatefromjpeg($originalImage);
            break;
        case IMAGETYPE_GIF:
            $imageTmp=imagecreatefromgif($originalImage);
            break;
        case IMAGETYPE_BMP:
            $imageTmp=imagecreatefrombmp($originalImage);
            break;
        // Defaults to JPG
        default:
            $imageTmp=imagecreatefromjpeg($originalImage);
            break;
    }

    // quality is a value from 0 (worst) to 100 (best)
    imagejpeg($imageTmp, $outputImage, $quality);
    imagedestroy($imageTmp);

    return 1;
}

您必须启用 php_exif 扩展才能使用它。

【讨论】:

    【解决方案2】:

    来自 PhpTools:

    /**
     * @param string $source (accepted jpg, gif & png filenames)
     * @param string $destination
     * @param int $quality [0-100]
     * @throws \Exception
     */
    public function convertToJpeg($source, $destination, $quality = 100) {
    
        if ($quality < 0 || $quality > 100) {
            throw new \Exception("Param 'quality' out of range.");
        }
    
        if (!file_exists($source)) {
            throw new \Exception("Image file not found.");
        }
    
        $ext = pathinfo($source, PATHINFO_EXTENSION);
    
        if (preg_match('/jpg|jpeg/i', $ext)) {
            $image = imagecreatefromjpeg($source);
        } else if (preg_match('/png/i', $ext)) {
            $image = imagecreatefrompng($source);
        } else if (preg_match('/gif/i', $ext)) {
            $image = imagecreatefromgif($source);
        } else {
            throw new \Exception("Image isn't recognized.");
        }
    
        $result = imagejpeg($image, $destination, $quality);
    
        if (!$result) {
            throw new \Exception("Saving to file exception.");
        }
    
        imagedestroy($image);
    }
    

    【讨论】:

      【解决方案3】:

      以所需图像质量将image.png 转换为image.jpg 的小代码:

      <?php
      $image = imagecreatefrompng('image.png');
      imagejpeg($image, 'image.jpg', 70); // 0 = worst / smaller file, 100 = better / bigger file 
      imagedestroy($image);
      ?>
      

      【讨论】:

        【解决方案4】:

        对大卫的回答的一个小修复,从 BMP 转换的正确函数是“imagecreatefromwbmp”而不是 imagecreatefrombmp(缺少“w”) 您还应该考虑 png 可能是透明的,here is 一种用白色 BG 填充它的方法(jpeg 不能应用 alpha 数据)。

        function convertImage($originalImage, $outputImage, $quality){
        // jpg, png, gif or bmp?
        $exploded = explode('.',$originalImage);
        $ext = $exploded[count($exploded) - 1]; 
        if (preg_match('/jpg|jpeg/i',$ext)){$imageTmp=imagecreatefromjpeg($originalImage);}
        else if (preg_match('/png/i',$ext)){$imageTmp=imagecreatefrompng($originalImage);}
        else if (preg_match('/gif/i',$ext)){$imageTmp=imagecreatefromgif($originalImage);}
        else if (preg_match('/bmp/i',$ext)){$imageTmp=imagecreatefromwbmp($originalImage);}
        else    {    return false;}
        // quality is a value from 0 (worst) to 100 (best)
        imagejpeg($imageTmp, $outputImage, $quality);
        imagedestroy($imageTmp);
        return true;
        }
        

        【讨论】:

          【解决方案5】:

          试试这个代码:originalImage 是……原始图像的路径……outputImage 足以自我解释。 Quality 是一个从 0 到 100 的数字,设置输出 jpg 质量(0 - 最差,100 - 最好)

          function convertImage($originalImage, $outputImage, $quality)
          {
              // jpg, png, gif or bmp?
              $exploded = explode('.',$originalImage);
              $ext = $exploded[count($exploded) - 1]; 
          
              if (preg_match('/jpg|jpeg/i',$ext))
                  $imageTmp=imagecreatefromjpeg($originalImage);
              else if (preg_match('/png/i',$ext))
                  $imageTmp=imagecreatefrompng($originalImage);
              else if (preg_match('/gif/i',$ext))
                  $imageTmp=imagecreatefromgif($originalImage);
              else if (preg_match('/bmp/i',$ext))
                  $imageTmp=imagecreatefrombmp($originalImage);
              else
                  return 0;
          
              // quality is a value from 0 (worst) to 100 (best)
              imagejpeg($imageTmp, $outputImage, $quality);
              imagedestroy($imageTmp);
          
              return 1;
          }
          

          【讨论】:

          • 调用这个函数而不是 move_uploaded_file
          • 使用 $ext == 'png' 和 like 代替 preg_match - 它也可以工作并且速度稍快一些。另外,我在检查前在 $ext 上使用 strtolower 来正确处理 .JPG 之类的扩展名。否则,出色的功能对我帮助很大。 +1
          • preg_match 中的 /i 使检查不区分大小写
          • 人们可能会认为传递 $_FILES['photoimg']['tmp_name'] 作为 $originalImage 会起作用,但它恰好将文件保存为 XXXXX.tmp,所以扩展名没有工作。改为传递 $_FILES['photoimg']['name'] 将给出正确的扩展名,但无法创建图像(它获取的是字符串而不是对象。所以要解决这个问题,您可以同时传递信息 $originalImage 和$originalName 并相应地编辑函数,除此之外,非常感谢 Davide 提供了我多年来一直使用的出色函数
          • 我会在每个 reg 的末尾添加 $ 符号。图案。为什么?上传的文件名为:iAmjpegWithGifAndPngTypedInName.bmp。美元符号将确保pattern中匹配的扩展名之后没有任何内容
          【解决方案6】:

          尝试使用ImagicksetImageFormat,对我来说它提供了最好的图像质量
          http://php.net/manual/en/imagick.setimageformat.php

          $im = new imagick($image);
          
          // convert to png
          $im->setImageFormat('png');
          
          //write image on server
          $im->writeImage($image .".png");
          $im->clear();
          $im->destroy(); 
          

          【讨论】:

            猜你喜欢
            • 2011-06-30
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-01-08
            • 2018-05-10
            • 2012-06-01
            • 2018-08-26
            相关资源
            最近更新 更多