Reputation: 237
I want to calculate the average color of an image (png or jpg) in php.
I want a little script that will go fast to calculate the average color.
I tried by resizing an image to 1px by 1px but I didn't have success. I always have an error like this : imagesx() expects parameter 1 to be resource, string given in
Here is my php:
$post_thumb = wp_get_attachment_url( get_post_thumbnail_id() );
$img = $post_thumb;
$x = imagesx($img);
$y = imagesy($img);
$tmp_img = ImageCreateTrueColor(1,1);
ImageCopyResampled($tmp_img,$img,0,0,0,0,1,1,$x,$y);
$rgb = ImageColorAt($tmp_img,0,0);
I know it comes from my image var but I don't know how to resolve it...
Upvotes: 1
Views: 1323
Reputation: 237
I'v got it, it was a problem from my var object:
$img = @imagecreatefromstring(file_get_contents($post_thumb));
$x = imagesx($img);
$y = imagesy($img);
$tmp_img = ImageCreateTrueColor(1,1);
ImageCopyResampled($tmp_img,$img,0,0,0,0,1,1,$x,$y);
$rgb = ImageColorAt($tmp_img,0,0);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
Upvotes: 3
Reputation: 99
Lolo, this is the function I use to have the average color of a picture
function average($img)
{
$w = imagesx($img);
$h = imagesy($img);
$r = $g = $b = 0;
for($y = 0; $y < $h; $y += 2) {
for($x = 0; $x < $w; $x++) {
$rgb = imagecolorat($img, $x, $y);
$r += $rgb >> 16;
$g += $rgb >> 8 & 255;
$b += $rgb & 255;
}
}
$pxls = $w * $h;
$r = dechex(round($r / $pxls));
$g = dechex(round($g / $pxls));
$b = dechex(round($b / $pxls));
if(strlen($r) < 2) {
$r = 0 . $r;
}
if(strlen($g) < 2) {
$g = 0 . $g;
}
if(strlen($b) < 2) {
$b = 0 . $b;
}
return "#" . $r . $g . $b;
}
Upvotes: 0