dsakktdog498483070 2016-11-19 19:36
浏览 38
已采纳

Laravel 5 - 在helpers.php中使用Package

I have this ColorThief\ColorThief package that works well inside a controller.

However, I want to create a function getImageColor($imgName) in helper.php to consume ColorThief\ColorThief so I can use getImageColor($imgName) directly from views.

How can I access ColorThief\ColorThief from inside 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;
}

When I call getImageColor('image.jpg'), I get the following error:

htmlspecialchars() expects parameter 1 to be string, array given (View: /home/userxyz/public_html/dev/resources/views/welcome.blade.php)

Please note that when ColorThief::getColor($upload_path); is used inside a controller, it works perfectly.

  • 写回答

1条回答 默认 最新

  • dscjp19831212 2016-11-19 22:08
    关注

    In your helper.php you can use it like this:

    use ColorThief\ColorThief;
    
    function getImageColor($sourceImage)
    {
        return ColorThief::getColor($sourceImage);
    }
    

    The $sourceImage variable must contain either the absolute path of the image on the server, a URL to the image, a GD resource containing the image, an Imagick image instance, a Gmagick image instance, or an image in binary string format. Package Github Repository.

    Update:

    This function returns an array of three integer values, corresponding to the RGB values (Red, Green & Blue) of the dominant color. Example: array(r: num, g: num, b: num)

    Further to convert the RGB to HEX you may use the following function:

    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;
    }
    

    For example:

    $color = rgb2hex(getImageColor($sourceImage)); // #ffffff for white
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?