You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用imagine-svg PHP库修改SVG颜色?

使用imagine-svg修改SVG颜色的问题解决方法

问题场景

我用imagine-svg调整SVG尺寸时,想把黑色SVG改成红色,但找不到colorize方法的正确用法。初始代码如下:

$imagine = new Imagine();
$image = $imagine->open($svg_file);
$image->resize(new Box(300, 300));

// 尝试调用colorize但报错
// $image->effects()->colorize($image->palette(), array(255,0,0));

$image->save($file_path);

报错信息

调用注释里的colorize代码时,触发类型错误:

Argument 1 passed to Contao\ImagineSvg\Effects::colorize() must be an instance of Imagine\Image\Palette\Color\ColorInterface, instance of Imagine\Image\Palette\RGB given, called in /var/www/html/site/public_html/wp-content/plugins/icon-svg-calculator/woo.php on line 369 and defined in /var/www/html/site/public_html/wp-content/plugins/icon-svg-calculator/vendor/contao/imagine-svg/src/Effects.php:83

正确实现方式

通过palette()->color()方法生成符合要求的ColorInterface实例,传入colorize即可完成颜色替换。修改后的完整代码:

$imagine = new Imagine();
$image = $imagine->open($svg_file);
$image->resize(new Box(300, 300));

// 将SVG替换为红色
$color_code = '#ff0000';
$image->effects()->colorize($image->palette()->color($color_code));

$image->save($file_path);

内容的提问来源于stack exchange,提问作者Rashid Bhura

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 17:05:20