你是否也曾遇到这样的场景:为了适配不同设备、不同区域的显示需求,你的网站需要展示同一张图片的不同尺寸、不同裁剪方式,甚至加上各种滤镜?如果每次都手动上传、手动处理这些图片,那简直是噩梦!为了解决这个问题,很多团队会选择使用像 thumbor 这样的图片处理服务。它允许你通过简单的url参数,在图片请求时动态进行裁剪、缩放、加滤镜等操作,极大地方便了图片管理。
然而,新的问题随之而来:如何生成这些复杂的 Thumbor URL?一个典型的 Thumbor URL 看起来是这样的:
http://thumbor.example.com:1234/OFDRoURwi9WVbZNfeOJVfIKr1Js=/fit-in/640x480/filters:fill(green)/http://images/example.com/llamas.jpg
这里面不仅有服务器地址、原始图片地址,还有各种处理参数(
fit-in
640x480
filters:fill(green)
OFDRoURwi9WVbZNfeOJVfIKr1Js=
终于,我找到了救星:99designs/phumbor
99designs/phumbor
99designs/phumbor
首先,你需要通过 Composer 将
99designs/phumbor
<pre class="brush:php;toolbar:false;">composer require 99designs/phumbor
安装完成后,你就可以开始生成 Thumbor URL 了。
99designs/phumbor
假设你的 Thumbor 服务器地址是
http://thumbor.example.com:1234
my-secret-key
http://images.example.com/llamas.jpg
<pre class="brush:php;toolbar:false;"><?php
require 'vendor/autoload.php';
use Thumbor\Url\Builder;
$server = 'http://thumbor.example.com:1234';
$secret = 'my-secret-key';
$imageUrl = 'http://images.example.com/llamas.jpg';
$thumborUrl = Builder::construct($server, $secret, $imageUrl)
->fitIn(640, 480) // 适应框内尺寸,最大640x480
->addFilter('fill', 'green') // 填充绿色背景
->__toString(); // 或者直接 echo
echo $thumborUrl;
// 预期输出:http://thumbor.example.com:1234/OFDRoURwi9WVbZNfeOJVfIKr1Js=/fit-in/640x480/filters:fill(green)/http://images.example.com/llamas.jpg看到没?通过链式调用,你可以非常直观地表达你对图片的处理需求。
fitIn()
addFilter()
99designs/phumbor
如果你需要在应用的多个地方生成 Thumbor URL,并且它们都使用相同的服务器和密钥,那么每次都重复
Builder::construct
99designs/phumbor
BuilderFactory
<pre class="brush:php;toolbar:false;"><?php
require 'vendor/autoload.php';
use Thumbor\Url\BuilderFactory;
$server = 'http://thumbor.example.com:1234';
$secret = 'my-secret-key';
// 创建一个工厂实例,复用服务器地址和密钥
$thumbnailUrlFactory = BuilderFactory::construct($server, $secret);
// 使用工厂生成第一个URL
echo $thumbnailUrlFactory
->url('http://images.example.com/llamas.jpg')
->fitIn(640, 480)
->addFilter('fill', 'green')
->__toString();
echo "\n";
// 使用工厂生成第二个URL,无需重复配置服务器和密钥
echo $thumbnailUrlFactory
->url('http://images.example.com/butts.png')
->crop(20, 20, 300, 300) // 裁剪区域 (x, y, width, height)
->valign('middle') // 垂直居中对齐
->__toString();通过
BuilderFactory
通过
99designs/phumbor
99designs/phumbor
以上就是如何优雅地生成Thumbor图片处理URL?99designs/phumbor助你轻松搞定!的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号