codewithkyle / jitter
即时图像转换服务。
Requires
- php: ^8.0
- aws/aws-sdk-php: ^3.0.0
- codewithkyle/jitter-core: ^2.0.0
- craftcms/cms: ^4.0
README
Jitter 是 Craft CMS 的即时图像转换插件。该 API 基于 Imgix。此插件是为了提供一个简单且免费的替代服务,类似于 Imgix。它 不会也不将 提供其他付费服务/插件所具有的所有功能和特性。如果您需要比基本图像转换更高级的功能,我建议您为 Imgix 支付费用或选择不同的 Craft 插件。
要求
此插件需要 ImageMagick 以及以下版本的 PHP 和 Craft CMS
- Craft CMS 4.0.0+ 与 PHP 8+ (Jitter v2.0+, 正在活跃)
- Craft CMS 3.0.0+ 与 PHP 7.2+ (Jitter v1.x, 不受支持)
安装
要安装此插件,请按照以下说明操作。
-
打开您的终端并转到您的 Craft 项目
cd /path/to/project
-
然后告诉 Composer 加载插件
composer require codewithkyle/jitter
-
在控制面板中,转到设置 → 插件,并点击 Jitter 的“安装”按钮。
配置 Jitter
Jitter 可以通过向项目的 config/
目录中添加一个 jitter.php
文件来配置为使用与 S3 兼容的对象存储解决方案。转换后的图像将存储在存储解决方案中,但仍然从您的 Web 服务器提供服务。如果您希望从 CDN 提供图像,请参阅下面的部分。
<?php return [ "accessKey" => getenv("PUBLIC_KEY"), "secretAccessKey" => getenv("PRIVATE_KEY"), "region" => "region-name", "bucket" => "bucket-name", "folder" => "transformed-images", "endpoint" => getenv("ENDPOINT_URL"), "acl" => "private", // supports "private" or "public-read" ];
注意:配置值
endpoint
和acl
是可选的。您只有在使用与 S3 兼容的替代 S3 云对象存储解决方案(如 Digital Ocean Spaces)时才需要使用endpoint
。
使用内容分发网络 (CDN)
Jitter 可以配置为使用 CDN URL。配置值 cdn
应该是 CDN 的源 URL。Jitter 的 url()
和 srcset()
函数将在图像转换执行过程中自动将使用 /jitter/
URL 切换到 CDN URL。
<?php return [ "accessKey" => getenv("PUBLIC_KEY"), "secretAccessKey" => getenv("PRIVATE_KEY"), "region" => "region-name", "bucket" => "bucket-name", "folder" => "transformed-images", "endpoint" => getenv("ENDPOINT_URL"), "acl" => "public-read", "cdn" => "https://demo.cdn.example.com/" ];
注意:如果您使用 Craft 的模板缓存或第三方 HTML 缓存服务(如 Cloudflare 的 Edge Cache),当可用的 CDN URL 时,
/jitter/
图像 URL 可能会被缓存。我们不推荐禁用您的缓存系统,但是您可能希望考虑使用更低的 TTL 以确保 CDN URL 更快地传播。
使用 Jitter
通过 API 进行图像转换
/jitter/v1/transform?id=1&w=768&ar=16:9
通过 Twig 进行图像转换
{# This will transform the image when the template renders. #} {# This can cause site-wide performance issues depending on how many times this method is used (per template) and how much RAM is available. #} {% set transformedImageUrl = craft.jitter.transformImage(entry.image[0], { w: 150, ar: "1:1", m: "fit", fm: "gif", q: 10 }) %} {# For a faster template render build the API URL instead #} {# If you have configured Jitter to use CDN URLs this value will swap to the CDN URL after the image has been transformed #} {% set transformedImageUrl = craft.jitter.url(entry.image[0], { w: 150, ar: "1:1", m: "fit", fm: "gif", q: 10 }) %} <img src="{{ transformedImageUrl }}" srcset="{{ craft.jitter.srcset(entry.image[0], [ { w: 300, h: 250, }, { w: 768, ar: "16:9", }, { w: 1024, ar: "16:9", }, ]) }}" loading="lazy" width="1024" />
通过 PHP 进行图像转换
$jitter = new \codewithkyle\jitter\services\Transform(); $src = $jitter->generateURL([ "id" => $image->id, "w" => 300, "ar" => "1:1", ]); $srcset = $jitter->generateSourceSet($image, [ [ "w" => 300, "h" => 250, ], [ "w" => 768, "ar" => "16:9", ], [ "w" => 1024, "ar" => "16:9", ], ]);
转换参数
auto
格式类型将在服务器可以生成该格式且客户端浏览器支持该格式时返回 webp
图像。