获取图像颜色

9 php image colors

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

有任何人对此有经验吗?在PHP中.我是菜鸟,所以请解释一下.非常感谢

Tim*_*tle 23

查看GD功能.

这是循环像素以找到最常见颜色的解决方案.但是,您可以将图像调整为1像素 - 应该是平均颜色 - 对吗?

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>
Run Code Online (Sandbox Code Playgroud)

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

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

?>
Run Code Online (Sandbox Code Playgroud)

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