每当Silverstripe从图像中创建一个调整大小的版本时,系统也会生成该映像的webp版本。通过.htaccess,我可以用chrome浏览器将用户转发到这个webp image。
到目前为止,我的想法是扩展image.php类,问题是,扩展不能覆盖现有的方法。
我能做些什么吗?当我从模板调用$Image.setWidth(200)时,我还可以这样做吗,我的函数会运行?
我的目标仍然是防止改变所有可行的方法名称。$Image.webpSetWidth(200)将使用正常的图像扩展。但如果可能的话我会避免这样做的。
检查Image.php (和GD.php)是否有可能扩展它,但至少在Silverstripe 3.6中是不可能的。
更新:
由于布雷特的暗示,我被指引到了正确的方向。
<?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');
}
}
}
}
}这将创建一个webp副本,每当一个调整大小的映像被保存( jp(e)g/png格式)时。为了工作,必须使用适当的标志编译gdlib。此外,您还必须通过config.php将类添加到Image::set_backend("WebPGDBackend");中。
请记住,这将只是现在工作的图形,这将得到新的大小。
有了上述功能,就可以将.htaccess配置为将对理解webp的浏览器的jpeg/png请求转发到新图形。
我意识到下面的片段:
<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>发布于 2018-01-25 03:25:22
我不确定SS3.6是否有开箱即用的功能来产生这个功能,但是您可以使用ImagickBackend并通过扩展来修改它。
例如。
<?php
if(class_exists('Imagick')) {
class MyImagickBackend extends ImagickBackend {
// default format to use
private static $format = 'webp';
public function __construct($filename = null) {
parent::__construct($filename);
$this->setImageFormat( Config::inst()->get('MyImagickBackend','format') );
}
}然后,在_config.php中,您只需将后端设置为用于图像
Image::set_backend("MyImagickBackend");注意:--这需要安装ImageMagick并启用ImageMagick模块。
注意:没有直接测试,所以您可能需要为设置其他ImageMagick参数
参考资料:
Imagemagick Specific webp calls in PHP
http://php.net/manual/en/book.imagick.php
https://github.com/silverstripe/silverstripe-framework/blob/3.6/filesystem/ImagickBackend.php
https://stackoverflow.com/questions/48425699
复制相似问题