gpt4 book ai didi

php - 获取图像颜色

转载 作者:可可西里 更新时间:2023-10-31 23:03:47 24 4
gpt4 key购买 nike

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

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

最佳答案

查看 GD functions .

这是 looping through the pixels 的解决方案找到最常见的颜色。然而,you could just resize the image to 1 pixel - 那应该是平均颜色 - 对吗?

1px 方法的示例(现在包括测试页):

<?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);

?>

更新:我放了一些more refined code on github .这包括平均边界和平均整个图像。应该注意的是,调整到 1px 比扫描每个像素更节省资源(虽然我没有运行任何实时测试),但代码确实显示了三种不同的方法。

关于php - 获取图像颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1746530/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com