加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

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

发布时间:2020-12-13 17:22:13 所属栏目:PHP教程 来源:网络整理
导读:我试图找到一种方法来使用 PHP从图像中获取边框颜色 我试图使用这个代码,但这个algorathim给了我任何图像的所有颜色. ?php function colorPalette($imageFile,$numColors,$granularity = 5) { $granularity = max(1,abs((int)$granularity)); $colors = arra
我试图找到一种方法来使用 PHP从图像中获取边框颜色

我试图使用这个代码,但这个algorathim给了我任何图像的所有颜色.

<?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),$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";

此外,我正在尝试使用它来构建像这些设计的设计.

解决方法

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

function checkColorAt(&$img,$y,&$colors) {
    $thisColor = imagecolorat($img,$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',$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,$0,&$colors);
    checkColorAt(&$img,$size[1] - 1,&$colors);
}

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读