将 JPG 转换为 PNG 并压缩的问题 | PHP

问题描述

基本上,我想将图像上传到网络服务器,并尽可能多地将其从 JPG 转换为 PNG。

以下是我目前必须从移动设备上传 JPG 图像的内容

<?PHP
  if(!empty($_FILES['uploaded_file']))
  {
    
    $path = "uploads/";
    $path = $path . basename( $_FILES['uploaded_file']['name']);
    if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$path)) {
      echo "The file ".  basename( $_FILES['uploaded_file']['name']).
      " has been uploaded";
    } else{
        echo "There was an error uploading the file,please try again!";
    }
  }
?>

这很有效,但我现在必须将文件转换为 PNG 并压缩 - 为此,我尝试使用这样的代码,但我不明白如何实现它并添加压缩。

 $image = imagecreatefromjpeg( "image.jpg" );
 imagealphablending($image,true);
 imagepng($image,"image.png");

是否可以进行转换和压缩?

解决方法

在官方 php 文档中:https://www.php.net/imagepng

据说imagepng的函数签名是:

imagepng ( resource $image,mixed $to = null,int $quality = -1,int $filters = -1 ) : bool

参数质量:

- quality

    Compression level: from 0 (no compression) to 9. 
    The default (-1) uses the zlib compression default. 
    For more information see the » zlib manual.

因此,当您在下面的代码中将图像保存为 PNG 时,它已经被压缩了:

 $image = imagecreatefromjpeg( "image.jpg" );
 imagealphablending($image,true);
 imagepng($image,"image.png");

如果你想要更高的压缩率(即:更小的尺寸,更差的图像质量),那么你只需要在质量参数中设置更高的数字(接近 9 = 更重的压缩)

 $image = imagecreatefromjpeg( "image.jpg" );
 imagealphablending($image,"image.png",9); // heavily compressed

您需要注意 imagejpeg https://www.php.net/imagejpeg 也有 quality 参数,但该参数的范围从 0(质量最差,文件较小)到 100(质量最佳,文件最大) ).