php - 在PHP中查找图像边框颜色的算法

标签 php gd

我正在尝试找到一种使用 php

从图像中获取边框颜色的方法

我曾尝试使用此代码,但此算法为我提供了任何图像中的所有颜色。

<?php 
function colorPalette($imageFile, $numColors, $granularity = 5) 
{ 
   $granularity = max(1, abs((int)$granularity)); 
   $colors = array(); 
   $size = @getimagesize($imageFile); 
   if($size === false) 
   { 
      user_error("Unable to get image size data"); 
      return false; 
   } 
   $img = @imagecreatefromjpeg($imageFile); 
   if(!$img) 
   { 
      user_error("Unable to open image file"); 
      return false; 
   } 
   for($x = 0; $x < $size[0]; $x += $granularity) 
   { 
      for($y = 0; $y < $size[1]; $y += $granularity) 
      { 
         $thisColor = imagecolorat($img, $x, $y); 
         $rgb = imagecolorsforindex($img, $thisColor); 
         $red = round(round(($rgb['red'] / 0x33)) * 0x33);  
         $green = round(round(($rgb['green'] / 0x33)) * 0x33);  
         $blue = round(round(($rgb['blue'] / 0x33)) * 0x33);  
         $thisRGB = sprintf('%02X%02X%02X', $red, $green, $blue); 
         if(array_key_exists($thisRGB, $colors)) 
         { 
            $colors[$thisRGB]++; 
         } 
         else 
         { 
            $colors[$thisRGB] = 1; 
         } 
      } 
   } 
   arsort($colors); 
   return array_slice(array_keys($colors), 0, $numColors); 
} 
// sample usage: 
$palette = colorPalette('rmnp8.jpg', 10, 4); 
echo "<table>\n"; 
foreach($palette as $color) 
{ 
   echo "<tr><td style='background-color:#$color;width:2em;'>&nbsp;</td><td>#$color</td></tr>\n"; 
} 
echo "</table>\n";

此外,我正在尝试使用它来构建类似这些设计的设计。

first second

最佳答案

您获得图像中所有颜色的原因是因为您使用嵌套循环来迭代图像中的像素。相反,您应该使用两个顺序循环:一个检查水平边界,另一个检查垂直边界,因此您的循环代码将变成如下所示:

function checkColorAt(&$img, $x, $y, &$colors) {
    $thisColor = imagecolorat($img, $x, $y); 
    $rgb = imagecolorsforindex($img, $thisColor); 
    $red = round(round(($rgb['red'] / 0x33)) * 0x33);  
    $green = round(round(($rgb['green'] / 0x33)) * 0x33);  
    $blue = round(round(($rgb['blue'] / 0x33)) * 0x33);  
    $thisRGB = sprintf('%02X%02X%02X', $red, $green, $blue); 
    if(array_key_exists($thisRGB, $colors)) 
    { 
        $colors[$thisRGB]++; 
    } 
    else 
    { 
        $colors[$thisRGB] = 1; 
    }
}


$colors = array();
for($x = 0; $x < $size[0]; $x += $granularity) 
{ 
    checkColorAt(&$img, $x, $0, &$colors);
    checkColorAt(&$img, $x, $size[1] - 1, &$colors);
}

for($y = 0; $y < $size[1]; $y += $granularity) 
{ 
    checkColorAt(&$img, $0, $y, &$colors);
    checkColorAt(&$img, $size[0] - 1, $y, &$colors);
}

关于php - 在PHP中查找图像边框颜色的算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13686990/

相关文章:

php - 如何在 Adob​​e-Brackets 中打开 PHP 自动完成

PHP GD图像透视

php - GD2 扩展是否随 PHP 一起提供?

php - 在 PHP 中裁剪图像

php - 将android应用程序连接到mysql数据库

javascript - 在 PHP 中解码字符串时出现意外行为(来自 AJAX POST 调用)

带有钠整数错误的PHP random_bytes

PHP:file_exists 和clearcachestat 给出错误的结果,直到服务器重新启动

php - 调整图像大小以完全适合尺寸(Codeigniter)

php - 复制图像变量 GD 库