gtarr/webp-parse-and-convert

0.3.2 2020-07-09 15:07 UTC

This package is auto-updated.

Last update: 2024-09-10 00:08:07 UTC


README

Packagist Downloads Packagist Version

通过库 WebP Convert 解析 HTML 页面并将图像转换为 WebP。

在服务器上检查转换为 WebP 的可能性

var_dump(function_exists('imagewebp')); // bool(true) - можно

如果服务器上没有 Imagick,则转换将正常工作,但输出图像的质量将不会与原始图像的质量相符(jpg 将设置为 75,png 将设置为 85)。

如果没有支持,则可以使用 这种方式

通过 Composer 安装

composer require gtarr/webp-parse-and-convert

不通过 Composer 安装

从这里 下载 并将 vendor 文件夹上传到网站

使用方法

  1. 默认情况
$content = '<html>...<img src="">...</html>'; // HTML страницы
$rootDir = $_SERVER['DOCUMENT_ROOT'];         // корень сайта

require $rootDir . '/vendor/autoload.php';

use WebPParseAndConvert\WebPParseAndConvert;

$converter = new WebPParseAndConvert($content);  

$content = $converter->execute();
  1. 附加选项(示例中显示默认值)
$rootDir = $_SERVER['DOCUMENT_ROOT'];

$options = [
   "formats" => ['jpg', 'jpeg', 'png'],
   "patterns" => [
      [
         'pattern' => '/<img[^>]+src=("[^"]*")[^>]*>/i',
         'exclude' => ['"', './']
      ],
      [
         'pattern' => '/background-image:.+url\(([^"]+)\)/i',
         'exclude' => ["'", "./"]
      ],
   ],
   "devices" => ['iphone', 'ipod', 'ipad', 'macintosh', 'mac os', 'Edge', 'MSIE', 'Trident'],
   "converterOptions" => [],
   "debug" => false,
   "useApi" => false,
   "api" => []
];

$converter = new WebPParseAndConvert($content, $rootDir, $options); 

选项

问题解决方案

当出现错误 PNG file skipped. GD is configured not to convert PNGs 时,需要禁用 PNG 图像的处理,这需要将 'formats' 选项设置为只包含 ['jpg', 'jpeg']
从版本 0.1.0 开始,这个异常会被捕获

用于 CMS 的示例

如果网站服务器不支持 WebP

可以在其他服务器上创建,该服务器支持转换为 WebP,可以使用云服务 webp-convert-cloud-service 并通过 API 调用它。为了使用这种方式,需要在 $options 中传递两个参数 useApiapi

$options = array(
    'useApi' => true,
    'api' => array(
       'key' => 'some API key',
       'url' => 'http://example.com/wpc.php'
    )
);

由于通过 cURL 发送/接收图像的长时间操作,不建议在动态更新信息的网站上持续使用此方法。