Reputation: 464
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.
Upvotes: 0
Views: 86
Reputation: 146191
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.
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
Upvotes: 1