Laravel 5 - 在helpers.php中使用Package

时间:2016-11-19 19:36:11

标签: php laravel-5

我有这个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);时,它可以正常运行

1 个答案:

答案 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