压缩 Web 图像并调整其大小



所以我目前正在使用php后端和聚合物前端构建一个网站。客户希望能够为自己的事件提供新闻功能。为此,我想将所有图像转换为 webp 并创建几种不同的大小,以便我可以将它们快速提供给不同的浏览器(手机、平板电脑、台式机等)。但是,我无法在PHP或JS中找到执行此操作的好方法。Squoosh 非常适合静态资产,但不适用于用户生成的内容。任何帮助感谢!

PHP 具有操作 webp 图像的函数。试试这个。

<?php
$im = imagecreatefromstring(file_get_contents('path/to/image.jpg')); // Create image identifier
imagewebp($im, 'path/to/image.webp'); // Generate webp image and save to location
imagedestroy($im); // Free up image identifier
?>

调整大小必须由服务器端完成。您可以做的是使用图像标记的srcsetsizes属性来优化要使用的版本:

<img srcset="elva-fairy-320w.jpg 320w,
             elva-fairy-480w.jpg 480w,
             elva-fairy-800w.jpg 800w"
     sizes="(max-width: 320px) 280px,
            (max-width: 480px) 440px,
            800px"
     src="elva-fairy-800w.jpg" alt="Elva dressed as a fairy" />

(直接来自 Mozilla 文档)

我强烈建议使用Adobe Photoshop。有了这个,您可以手动压缩/调整图像大小或批量提交它们。

我不知道

您是否可以访问服务器,但一种方法是从PHP调用ImageMagick。PHP需要与服务器交互,这可能是危险的,所以请记住这一点。

据我所知,ImageMagick虽然不支持webm,但我相信你明白背后的想法。

如果您不希望 PHP 与服务器本身交互,您还可以扫描未转换/调整大小的图像,然后转换它们。在 Linux 上,它可能是:查找 ./-name "*.jpg" -exec CONVERT_FUNCTION{} \;

要调整图像大小和压缩图像,您需要随PHP一起安装图像库,例如ImageMagick或GD

您可以编写自己的调整大小函数,如 https://stackoverflow.com/a/14649689 所示,但必须小心图像类型,因为它们可能具有每种类型自己的函数。

一种更简单的调整大小的方法是使用图像干预包。 https://image.intervention.io/v2/api/resize(这也需要安装 GD 或 IamgeMagick):

// resize image to fixed size
$img->resize(300, 200);
// resize only the width of the image
$img->resize(300, null);
// resize only the height of the image
$img->resize(null, 200);
// resize the image to a width of 300 and constrain aspect ratio (auto height)
$img->resize(300, null, function ($constraint) {
    $constraint->aspectRatio();
});

使用此库,您还可以使用编码或保存功能压缩图像:

https://image.intervention.io/v2/api/encode

https://image.intervention.io/v2/api/save

// open and resize an image file
$img = Image::make('public/foo.jpg')->resize(300, 200);
// save file as jpg with medium quality
$img->save('public/bar.jpg', 60);

您也可以使用tinypng API来压缩图像:https://tinypng.com/developers,它可以压缩jpg,png和WebP,如果您每月缩放500张图像,则是免费的

最新更新