我想在div或表格中显示图像作为背景.如果他们的图像不够大,我将需要找到该图像的最外部颜色,并将其应用到包含div或表格单元格的背景.
有没有人有这方面的经验?在PHP中.我是一个noob所以请解释.非常感谢
查看
GD functions.
原文链接:https://www.f2er.com/php/132365.html这是looping through the pixels的一个解决方案,找到最常见的颜色.但是,you could just resize the image to 1 pixel – 应该是平均颜色 – 对吗?
<?PHP $filename = $_GET['filename']; $image = imagecreatefromjpeg($filename); $width = imagesx($image); $height = imagesy($image); $pixel = imagecreatetruecolor(1,1); imagecopyresampled($pixel,$image,1,$width,$height); $rgb = imagecolorat($pixel,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,$y); $color = imagecolorsforindex($image,$rgb); $red += $color['red']; $green += $color['green']; $blue += $color['blue']; $rgb = imagecolorat($image,$width -1,$rgb); $red += $color['red']; $green += $color['green']; $blue += $color['blue']; } for($x = 0; $x < $height; $x++){ $rgb = imagecolorat($image,$x,0); $color = imagecolorsforindex($image,$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); ?>
更新:我把一些more refined code on github.这包括平均边框,平均整个图像.应该注意的是,调整到1px的资源比扫描每个像素要好得多(虽然我没有运行任何实时测试),但代码确实显示了三种不同的方法.