0

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
  • a little confused on what you actually want because if you want a function to have a class object in it then you will instantiate it inside the function Commented Nov 19, 2016 at 19:43

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

It's happening in your welcome.blade.php blade template and this is happening because you are probably trying to echo something using {{ $someThing }} where $something is n array. The function is alright and error is in your view. Notice the return value of the function call, which is an array like returns array(r: num, g: num, b: num), so if you try to echo the return value then it'll not work. Check the documentation (Github) to learn more about this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.