[每当Silverstripe从图像中创建调整大小的版本时,系统还将生成该图像的webp版本。然后,我可以通过.htaccess
将带有Chrome浏览器的用户转发到此webp image
。
到目前为止,我的想法是扩展image.php
类,问题是,扩展不能覆盖现有方法。
有什么办法可以做些事情,以便当我从模板调用$Image.setWidth(200)
时仍可以执行此操作,我的函数将运行?
我的目标仍然是防止更改所有可行的方法名称。$Image.webpSetWidth(200)
适用于普通的图像扩展名。但是,如果可以的话,我会避免这种情况。
检查了Image.php
(和GD.php
)是否可以扩展它,但至少在Silverstripe 3.6
中是不可能的。
UPDATE:
由于布雷特的提示,我指出了正确的方向。
<?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请求转发到新图形。
我意识到,使用以下代码段:
<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>
我不确定SS 3.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并启用PHP模块。
NOTE:此未经直接测试,因此您可能需要为webp设置其他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