获取图像颜色

我想要在div或表格中显示图像作为背景。 如果他们的图像不够大,我将需要find该图像的最外层颜色,并将其应用于包含div或表格单元格的背景。

有没有人有这方面的经验? 在PHP中。 我是一个小菜,所以请解释。 非常感谢

检查GDfunction 。

这是一个循环遍历像素的解决scheme,以find最常见的颜色。 但是, 您可以将图像调整为1像素 – 应该是平均颜色 – 对吧?

1px方法( 现在包括testing页 )的一个例子:

<?php $filename = $_GET['filename']; $image = imagecreatefromjpeg($filename); $width = imagesx($image); $height = imagesy($image); $pixel = imagecreatetruecolor(1, 1); imagecopyresampled($pixel, $image, 0, 0, 0, 0, 1, 1, $width, $height); $rgb = imagecolorat($pixel, 0, 0); $color = imagecolorsforindex($pixel, $rgb); ?> <html> <head> <title>Test Image Average Color</title> </head> <body style='background-color: rgb(<?php echo $color['red'] ?>, <?php echo $color['green'] ?>, <?php echo $color['blue'] ?>)'> <form action='' method='get'> <input type='text' name='filename'><input type='submit'> </form> <img src='<?php echo $filename ?>'> </body> </html> 

以下是一些用于查找平均边框颜色的示例代码,与第一个链接相似。 为了您的使用,这可能会更好( 我知道这个代码是低效的,但希望它很容易遵循 ):

 <?php $filename = $_GET['filename']; $image = imagecreatefromjpeg($filename); $width = imagesx($image); $height = imagesy($image); for($y = 0; $y < $height; $y++){ $rgb = imagecolorat($image, 0, $y); $color = imagecolorsforindex($image, $rgb); $red += $color['red']; $green += $color['green']; $blue += $color['blue']; $rgb = imagecolorat($image, $width -1, $y); $color = imagecolorsforindex($image, $rgb); $red += $color['red']; $green += $color['green']; $blue += $color['blue']; } for($x = 0; $x < $height; $x++){ $rgb = imagecolorat($image, $x, 0); $color = imagecolorsforindex($image, $rgb); $red += $color['red']; $green += $color['green']; $blue += $color['blue']; $rgb = imagecolorat($image, $x, $height -1); $color = imagecolorsforindex($image, $rgb); $red += $color['red']; $green += $color['green']; $blue += $color['blue']; } $borderSize = ($height=$width)*2; $color['red'] = intval($red/$borderSize); $color['green'] = intval($green/$borderSize); $color['blue'] = intval($blue/$borderSize); ?> 

更新 :我把一些更精致的代码在github上 。 这包括平均边界和平均整个图像。 应该指出的是,调整到1像素是比扫描每个像素更为资源友好(虽然我没有运行任何实时testing),但代码确实显示了三种不同的方法。