【发布时间】:2019-12-07 13:33:11
【问题描述】:
每当 Silverstripe 从图像创建调整大小的版本时,系统也会生成该图像的 webp 版本。
通过.htaccess,我可以使用chrome浏览器将用户转发到webp image。
到目前为止,我的想法是扩展image.php 类,问题是扩展不能覆盖现有方法。
有什么方法可以让我在从模板中调用$Image.setWidth(200) 时仍然可以执行此操作,我的函数将运行?
我的目标仍然是防止更改所有可行的方法名。
$Image.webpSetWidth(200) 可以与普通图像扩展一起使用。但如果可能的话,我会避免这种情况。
检查了Image.php(和GD.php)是否有可能扩展它,但至少在Silverstripe 3.6 中是不可能的。
更新:
感谢 Brett 的提示,我找到了正确的方向。
<?php
class WebPGDBackend extends GDBackend
{
public function writeTo($filename)
{
parent::writeTo($filename);
if (function_exists('imagewebp')) {
$picname = pathinfo($filename, PATHINFO_FILENAME);
$directory = pathinfo($filename, PATHINFO_DIRNAME);
list($width, $height, $type, $attr) = getimagesize($filename);
switch ($type) {
case 2:
if (function_exists('imagecreatefromjpeg')) {
$img = imagecreatefromjpeg($filename);
$webp = imagewebp($img, $directory.'/'.$picname.'.webp');
$gif = imagegif($img, $directory.'/'.$picname.'.gif');
}
break;
case 3:
if (function_exists('imagecreatefrompng')) {
$img = imagecreatefrompng($filename);
imagesavealpha($img, true); // save alphablending setting (important)
$webp = imagewebp($img, $directory.'/'.$picname.'.webp');
}
}
}
}
}
每当保存调整大小的图像(以 jp(e)g/png 格式)时,这将创建一个 webp 副本。
为了使它工作,必须使用适当的标志编译 gdlib。
此外,您必须通过将类添加到 config.php
Image::set_backend("WebPGDBackend");.
请记住,这仅适用于新调整大小的图形。
有了上面的内容,就可以配置.htaccess以将理解webp的浏览器的jpeg/png请求转发到新图形。
我通过以下 sn-p 意识到这一点:
<IfModule mod_rewrite.c>
RewriteEngine On
# Check if browser support WebP images
RewriteCond %{HTTP_ACCEPT} image/webp
# Check if WebP replacement image exists
RewriteCond %{DOCUMENT_ROOT}/$1.webp -f
# Serve WebP image instead
RewriteRule (assets.+)\.(jpe?g|png)$ $1.webp [T=image/webp,E=accept:1]
</IfModule>
<IfModule mod_headers.c>
Header append Vary Accept env=REDIRECT_accept
</IfModule>
<IfModule mod_mime.c>
AddType image/webp .webp
</IfModule>
【问题讨论】:
标签: php silverstripe