使用 php (jpeg) 优化上传的图片

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14072456/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 06:34:23  来源:igfitidea点击:

Optimize uploaded images with php (jpeg)

phpgdjpegimage-compressionimage-optimization

提问by Juvlius

When running Page Speed in Google Chrome it suggests to optimize/compress the images. These images are mostly uploaded by users, so I would need to optimize them during uploading. What I find about optimizing jpeg images with php is something like using the following GD functions:

在 Google Chrome 中运行 Page Speed 时,它建议优化/压缩图像。这些图片大多由用户上传,所以我需要在上传过程中优化它们。我发现使用 php 优化 jpeg 图像类似于使用以下 GD 函数:

getimagesize()
imagecreatefromjpeg()
imagejpeg()

Since I am resizing the images after upload I'm already pulling the image through these functions and in addition I use imagecopyresampled()after imagecreatefromjpeg()to resize it.

由于我在上传后调整图像大小,因此我已经通过这些函数拉取图像,此外我还使用imagecopyresampled()afterimagecreatefromjpeg()来调整它的大小。

But then, Page Speed is still telling me these images can be optimized. How can I accomplish this optimisation in a php script? Set the quality lower in imagejpeg() doesn't make a difference either.

但是,Page Speed 仍然告诉我这些图像可以优化。如何在 php 脚本中完成此优化?在 imagejpeg() 中设置较低的质量也没有什么区别。

回答by Pez Cuckow

The imagejpeg function is where you assign the quality. If you're already setting that to an appropriate value then there is little else you can do.

imagejpeg 函数是您分配质量的地方。如果您已经将其设置为适当的值,那么您几乎无能为力。

Page speed probably considers all images above a certain size to be "needing compression", perhaps just ensure they are all as small as reasonable (in terms of height/width) and compressed.

页面速度可能认为所有超过特定大小的图像“需要压缩”,也许只是确保它们都尽可能小(在高度/宽度方面)并被压缩。

You can find more about page speed and it's compression suggestions on the pagespeed docs http://code.google.com/speed/page-speed/docs/payload.html#CompressImageswhich describes some of the techniques/tools to compress appropriately.

您可以在 pagespeed 文档http://code.google.com/speed/page-speed/docs/payload.html#CompressImages上找到有关页面速度及其压缩建议的更多信息,该文档描述了一些适当压缩的技术/工具。

I've also just read the following:

我也刚刚阅读了以下内容:

Several tools are available that perform further, losslesscompression on JPEG and PNG files, with no effect on image quality. For JPEG, we recommend jpegtranor jpegoptim(available on Linux only; run with the --strip-all option). For PNG, we recommend OptiPNGor PNGOUT.

有几种工具可以对 JPEG 和 PNG 文件执行进一步的无损压缩,而不会影响图像质量。对于 JPEG,我们推荐jpegtranjpegoptim(仅适用于 Linux;使用 --strip-all 选项运行)。对于 PNG,我们推荐OptiPNGPNGOUT

So perhaps (if you really want to stick to Google's suggestions) you could use PHP's execto run one of those tools on files as they are uploaded.

所以也许(如果你真的想坚持谷歌的建议)你可以使用 PHPexec来在文件上传时运行这些工具之一。



To compress with php you do the following (sounds like you are already doing this):

要使用 php 压缩,您可以执行以下操作(听起来您已经在这样做了):

Where $source_urlis the image, $destination_urlis where to save and $qualityis a number between 1 and 100 choosing how much jpeg compression to use.

$source_url图像在哪里,$destination_url在哪里保存,$quality是一个 1 到 100 之间的数字,用于选择使用多少 jpeg 压缩。

function compressImage($source_url, $destination_url, $quality) {
    $info = getimagesize($source_url);

    if ($info['mime'] == 'image/jpeg') $image = imagecreatefromjpeg($source_url);
    elseif ($info['mime'] == 'image/gif') $image = imagecreatefromgif($source_url);
    elseif ($info['mime'] == 'image/png') $image = imagecreatefrompng($source_url);

    //save file
    imagejpeg($image, $destination_url, $quality);

    //return destination file
    return $destination_url;
}

回答by Ferhad Konar

Repaired function:

修复功能:

function compressImage($source_url, $destination_url, $quality) {

    //$quality :: 0 - 100

    if( $destination_url == NULL || $destination_url == "" ) $destination_url = $source_url;

    $info = getimagesize($source_url);

    if ($info['mime'] == 'image/jpeg' || $info['mime'] == 'image/jpg')
    {
        $image = imagecreatefromjpeg($source_url);
        //save file
        //ranges from 0 (worst quality, smaller file) to 100 (best quality, biggest file). The default is the default IJG quality value (about 75).
        imagejpeg($image, $destination_url, $quality);

        //Free up memory
        imagedestroy($image);
    }
    elseif ($info['mime'] == 'image/png')
    {
        $image = imagecreatefrompng($source_url);

        imageAlphaBlending($image, true);
        imageSaveAlpha($image, true);

        /* chang to png quality */
        $png_quality = 9 - round(($quality / 100 ) * 9 );
        imagePng($image, $destination_url, $png_quality);//Compression level: from 0 (no compression) to 9(full compression).
        //Free up memory
        imagedestroy($image);
    }else
        return FALSE;

    return $destination_url;

}

回答by DevWL

You could use Imagick class for this. Consider following wrapper function:

您可以为此使用 Imagick 类。考虑以下包装函数:

<?php
    function resizeImage($imagePath, $width, $height, $blur, $filterType = Imagick::FILTER_LANCZOS, $bestFit = false)
    {
        //The blur factor where &gt; 1 is blurry, &lt; 1 is sharp.
        $img= new \Imagick(realpath($imagePath));
        $img->setCompression(Imagick::COMPRESSION_JPEG); 
        $img->setCompressionQuality(40);
        $img->stripImage();
        $img->resizeImage($width, $height, $filterType, $blur, $bestFit);
        $img->writeImage();
    }

?>

Read more on how to resize images with Imagick at:
http://php.net/manual/en/class.imagick.php
http://php.net/manual/en/imagick.resizeimage.phphttp://php.net/manual/en/imagick.constants.php#imagick.constants.filters

了解更多关于如何在与Imagick将图像尺寸调整:
http://php.net/manual/en/class.imagick.php
http://php.net/manual/en/imagick.resizeimage.php HTTP:// PHP .net/manual/en/imagick.constants.php#imagick.constants.filters

回答by user2970934

it is very important to optimize your images. Several CMS platforms out there have modules or plugins to preform this process. However if you are programming it yourself there is a complete php tutorial located at this page https://a1websitepro.com/optimize-images-with-php-in-a-directory-on-your-server/You will be shown how to implement the imagecreatefromjpeg($SrcImage);and imagecreatefrompng($SrcImage);and imagecreatefromgif($SrcImage);There are written and video instruction on the page.

优化图像非常重要。有几个 CMS 平台有模块或插件来执行这个过程。但是,如果您自己编程,则此页面上有一个完整的 php 教程https://a1websitepro.com/optimize-images-with-php-in-a-directory-on-your-server/您将看到如何落实imagecreatefromjpeg($SrcImage);imagecreatefrompng($SrcImage);imagecreatefromgif($SrcImage);有文字和视频教学网页上。