gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 01:07:13 25 4
gpt4 key购买 nike

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

getimagesize()
imagecreatefromjpeg()
imagejpeg()

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

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

最佳答案

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

页面速度可能会将所有超过一定尺寸的图像视为“需要压缩”,也许只是确保它们都尽可能小(在高度/宽度方面)并进行压缩。

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

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

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

因此,也许(如果您确实想遵循 Google 的建议)您可以使用 PHP 的 exec 在文件上传时对其运行这些工具之一。

<小时/>

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

其中 $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;
}

关于php - 使用 php (jpeg) 优化上传的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14072456/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com