php 转换为 3 位十六进制颜色代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1459273/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 02:40:28  来源:igfitidea点击:

convert to 3-digit hex color code

phpcsscolorshex

提问by eozzy

I've been using 3-digit hex color values in CSS for a long time: #fff, #999, #069, etc. I can see how the repeating letters/numbers are merged to create a 3-digit hex color code, but I don't fully understand the pattern to be able to write a converter in PHP. Is there documentation for this?

我一直在 CSS 中使用 3 位十六进制颜色值很长时间:#fff#999#069等。我可以看到重复的字母/数字如何合并以创建 3 位十六进制颜色代码,但我不完全了解模式以便能够在 PHP 中编写转换器。有这方面的文件吗?

Edit:Oh, perhaps my question wasn't clear. I need to know how some of the 6-digit hex color values are converted to 3-digits. xxxxxx(ffffff) and xxyyzz(006699) – these are the only two patterns, correct?

编辑:哦,也许我的问题不清楚。我需要知道一些 6 位十六进制颜色值是如何转换为 3 位的。xxxxxx( ffffff) 和xxyyzz( 006699) – 这是仅有的两种模式,对吗?

回答by Greg

To convert a 3-character hex code into a 6 character one, you need to repeat each character:

要将 3 个字符的十六进制代码转换为 6 个字符的十六进制代码,您需要重复每个字符:

$hex = '#fff';
$hex6 = '#' . $hex[1] . $hex[1] . $hex[2] . $hex[2] . $hex[3] . $hex[3];

If you want to convert it to decimal you can use the hexdecfunction

如果要将其转换为十进制,可以使用该hexdec函数

回答by Kobi

3 digit CSS code is short for 6 digits": #06a; is #0066aa;
Each two digits represent a number from 0 to 255.
Converting these values to hex and back is all you need.

3 位 CSS 代码是 6 位数字的缩写”:#06a; is #0066aa;
每两位数字代表一个从 0 到 255 的数字。
将这些值转换为十六进制并返回即可。

回答by jensgram

#f0fis expanded to #ff00ffso basically you just need to calculate the value and the value times 16 for each character, e.g.:

#f0f扩展为#ff00ff因此基本上您只需要计算每个字符的值和值乘以 16,例如:

#f98: f = 15 => red = 15 + 15*16 = 255 etc.

#f98: f = 15 => 红色 = 15 + 15*16 = 255 等等。

回答by Dan Mecklenburg

function hexfix(str) {
  var v, w;
  v = parseInt(str, 16); // in rrggbb
  if (str.length == 3) {
    // nybble colors - fix to hex colors
 //  0x00000rgb              -> 0x000r0g0b
 //  0x000r0g0b | 0x00r0g0b0 -> 0x00rrggbb
 w = ((v & 0xF00) << 8) | ((v & 0x0F0) << 4) | (v & 0x00F);
 v = w | (w << 4);
  }
  return v.toString(16).toUpperCase();
 }

var hex1 = 'AABBCC',
    hex2 = 'ABC';

document.body.appendChild(document.createTextNode(hex1+" becomes "+hexfix(hex1)+'.  '));
document.body.appendChild(document.createTextNode(hex2+" becomes "+hexfix(hex2)+'.  '));

Something like this.

像这样的东西。