2025年3月21日更新

自从用上阿里云的CDN+OSS并使用图片处理功能之后,WebP的问题也就随之解决了,交给CDN和OSS自动处理了。


2025年3月4日原文

这里说的WebP扩展并不是指让MediaWiki支持WebP格式(因为它默认就支持该格式),而是指将上传的图片转化成WebP并在前端显示。
为什么会想到用这个?因为WebP格式的图片比通常使用的jpg和png格式要小得多(尽管我曾对它有多么得不屑一顾)。

WebP 是一种现代图片格式,可为网络上的图片提供出色的无损和有损压缩。使用 WebP,网站站长和 Web 开发者可以创建更小、更丰富的图片,从而提高网页加载速度。

与 PNG 相比,WebP 无损图片的尺寸缩小了 26%。WebP 有损图片比采用等效 SSIM 质量指数的同等 JPEG 图片小 25-34%。

无损 WebP 支持透明度(也称为 Alpha 通道),但只需额外增加 22% 的字节。对于可以接受有损 RGB 压缩的情况,有损 WebP 也支持透明度,其文件大小通常比 PNG 小 3 倍。

好吧,我承认对它了解不深,哪怕它已经有十几年的历史了。而我终于意识到它,归根结底还是因为流量的不断增加。

一、安装WebP扩展

WebP扩展的发行状态为beta,但在https://star-citizen.wiki网站上已经被实际应用,加之作者曾开发过WikiSEO、TemplateStylesExtender等扩展,可靠性相对会高一点。
进入extensions目录后,运行git命令:

https://github.com/octfx/mediawiki-extension-WebP.git WebP

注意:在MediaWiki的插件页面上,作者提供的master版本可能存在兼容性问题,所以最好还是获取最新的代码。
在启用插件前还需要安装另外一个扩展PictureHtmlSupport。同样通过git方式下载到扩展目录中:

https://github.com/StarCitizenWiki/mediawiki-extensions-PictureHtmlSupport.git PictureHtmlSupport

打开配置文件LocalSettings.php,添加以下内容:

wfLoadExtension( 'PictureHtmlSupport' );

然后备份一下includes/media/ThumbnailImage.php文件(一定要备份,否则文件被覆盖后系统出错就没救了),并将该扩展下的includes/ThumbnailImage.php覆盖刚刚备份的文件。
再次打开配置文件LocalSettings.php,添加以下内容:

wfLoadExtension( 'WebP' );

二、配置和转换

根据扩展的文档,在配置文件中添加如下内容:

// Enables WebP creation after a new image was uploaded
$wgWebPEnableConvertOnUpload = true;

// Enables WebP creation after a thumbnail was created
$wgWebPEnableConvertOnTransform = true;

// Compression quality of the image: 0 - 100 where 100 means most compressed
$wgWebPCompressionQuality = 50;

// the strength of the deblocking filter, between 0 (no filtering) and 100 (maximum filtering). A value of 0 turns off any filtering. Higher values increase the strength of the filtering process applied after decoding the image. The higher the value, the smoother the image appears. Typical values are usually in the range of 20 to 50.
$wgWebPFilterStrength = 50;

// when enabled, the algorithm spends additional time optimizing the filtering strength to reach a well-balanced quality.
$wgWebPAutoFilter = true;

// Create images through the JobQueue
$wgWebPConvertInJobQueue = true;

// Thumbnail Sizes to create through the maintenance script
$wgWebPThumbSizes = [
   120,
   320,
   800,
   1200,
   1600
];

// Enabling the Avif transformer (requries libheif and imagick >= 6.9)
$wgEnabledTransformers = [
    "MediaWiki\\Extension\\WebP\\Transformer\\WebPTransformer",
    "MediaWiki\\Extension\\WebP\\Transformer\\AvifTransformer",
];

如果网站已经上传过图片,那么还需要进行转换。回到网站根目录下,运行以下命令:

php extensions/WebP/maintenance/CreateFromLocalFiles.php

不需要转换缩略图的话,可以添加--no-thumbs参数,即:

php extensions/WebP/maintenance/CreateFromLocalFiles.php --no-thumbs

整个转换过程可能会持续很久,可以通过查看images下的webpthumbs/webp目录进行确认。如果开启了Avif转换器,那么还会增加avif目录和thumbs/avif目录。
刷新页面,正常情况下会发现原有的标签被替换成<picture><img>两部分,并且增加两个<source>,如下图:
star-citizen.png
这是该扩展的样例站。
虽然我的最终结果也是如此,但不知什么原因,图片却无法正常显示,能显示的仍然为jpg格式的图片。并且有网友提出了同样的问题,但作者也没有给出明确的答复,只能暂且作罢。

最后修改:2025 年 03 月 21 日
如果觉得我的文章对你有用,请随意赞赏