我有这个ColorThief\ColorThief
包在控制器内运行良好。
但是,我想在getImageColor($imgName)
中创建一个函数helper.php
来使用ColorThief\ColorThief
,以便我可以直接从视图中使用getImageColor($imgName)
。
如何从ColorThief\ColorThief
内访问helper.php
。
use ColorThief\ColorThief;
function getImageColor($img='') {
if(!empty($img)) {
$upload_path = public_path() . '/uploads/'.$img;
if(file_exists($upload_path)) {
return ColorThief::getColor($upload_path);
}
}
return false;
}
当我致电getImageColor('image.jpg')
时,我收到以下错误:
htmlspecialchars()期望参数1为字符串,给定数组(查看:/home/userxyz/public_html/dev/resources/views/welcome.blade.php)
请注意,在控制器内部使用ColorThief::getColor($upload_path);
时,它可以正常运行。
答案 0 :(得分:1)
在helper.php
中,您可以像这样使用它:
use ColorThief\ColorThief;
function getImageColor($sourceImage)
{
return ColorThief::getColor($sourceImage);
}
$ sourceImage变量必须包含的绝对路径 服务器上的图像,图像的URL,包含的GD资源 图像,Imagick图像实例,Gmagick图像实例或 二进制字符串格式的图像。 Package Github Repository
此函数返回三个整数值的数组,对应 到主色的RGB值(红色,绿色和蓝色)。例:
array(r: num, g: num, b: num)
要将RGB
转换为HEX
,您可以使用以下功能:
function rgb2hex($rgb)
{
$hex .= str_pad(dechex($rgb[0]), 2, "0", STR_PAD_LEFT);
$hex .= str_pad(dechex($rgb[1]), 2, "0", STR_PAD_LEFT);
$hex .= str_pad(dechex($rgb[2]), 2, "0", STR_PAD_LEFT);
return "#".$hex;
}
例如:
$color = rgb2hex(getImageColor($sourceImage)); // #ffffff for white