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 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 Macbookpro 连接热点正常上网,连接不了Wi-Fi。
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义