gpt4 book ai didi

php - 在 PHP 中对相似的十六进制代码进行分组

转载 作者:可可西里 更新时间:2023-11-01 13:24:38 26 4
gpt4 key购买 nike

我有以下颜色代码:

f3f3f3
f9f9f9

从视觉上看,这两种颜色代码很相似。如何将它们组合成一种颜色,或删除其中一个?

如果我尝试使用 base_convert($hex, 16, 10) 并获取值之间的差异,问题是某些颜色与 int 值相似但在视觉上确实不同。例如:

#484848 = 4737096 (grey)
#4878a8 = 4749480 (blue) - visually there is a huge difference, but as int value the difference is small

#183030 = 1585200 (greyish)
#181818 = 1579032 (greyish) - both ways is fine

#4878a8 = 4749480 (blue)
#a81818 = 11016216 (red) - the difference is huge, both visual and as int value

最佳答案

使用hexdec将十六进制颜色代码转换为其等效的 RGB 函数。示例(取自 hexdec 页面):

<?php
/**
* Convert a hexa decimal color code to its RGB equivalent
*
* @param string $hexStr (hexadecimal color value)
* @param boolean $returnAsString (if set true, returns the value separated by the separator character. Otherwise returns associative array)
* @param string $seperator (to separate RGB values. Applicable only if second parameter is true.)
* @return array or string (depending on second parameter. Returns False if invalid hex color value)
*/
function hex2RGB($hexStr, $returnAsString = false, $seperator = ',') {
$hexStr = preg_replace("/[^0-9A-Fa-f]/", '', $hexStr); // Gets a proper hex string
$rgbArray = array();
if (strlen($hexStr) == 6) { //If a proper hex code, convert using bitwise operation. No overhead... faster
$colorVal = hexdec($hexStr);
$rgbArray['red'] = 0xFF & ($colorVal >> 0x10);
$rgbArray['green'] = 0xFF & ($colorVal >> 0x8);
$rgbArray['blue'] = 0xFF & $colorVal;
} elseif (strlen($hexStr) == 3) { //if shorthand notation, need some string manipulations
$rgbArray['red'] = hexdec(str_repeat(substr($hexStr, 0, 1), 2));
$rgbArray['green'] = hexdec(str_repeat(substr($hexStr, 1, 1), 2));
$rgbArray['blue'] = hexdec(str_repeat(substr($hexStr, 2, 1), 2));
} else {
return false; //Invalid hex color code
}
return $returnAsString ? implode($seperator, $rgbArray) : $rgbArray; // returns the rgb string or the associative array
} ?>

输出:

hex2RGB("#FF0") -> array( red =>255, green => 255, blue => 0)
hex2RGB("#FFFF00) -> Same as above
hex2RGB("#FF0", true) -> 255,255,0
hex2RGB("#FF0", true, ":") -> 255:255:0

然后,获取红色、绿色和蓝色增量,以获得颜色距离。

关于php - 在 PHP 中对相似的十六进制代码进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13747841/

26 4 0
文章推荐: c++ - 在 C++ 中发送崩溃报告、产品注册等的正常方法是什么?
文章推荐: html -
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com