最有效的方法是什么?
在python中:
def hex_to_rgb(value): """Return (red, green, blue) for the color given as #rrggbb.""" value = value.lstrip('#') lv = len(value) return tuple(int(value[i:i + lv // 3], 16) for i in range(0, lv, lv // 3)) def rgb_to_hex(red, green, blue): """Return color as #rrggbb for the given color values.""" return '#%02x%02x%02x' % (red, green, blue) hex_to_rgb("#ffffff") #==> (255, 255, 255) hex_to_rgb("#ffffffffffff") #==> (65535, 65535, 65535) rgb_to_hex(255, 255, 255) #==> '#ffffff' rgb_to_hex(65535, 65535, 65535) #==> '#ffffffffffff'
在python中,hex和'rgb'之间的转换也包含在绘图包中matplotlib
.亦即
import matplotlib.colors as colors
然后
colors.hex2color('#ffffff') #==> (1.0, 1.0, 1.0) colors.rgb2hex((1.0, 1.0, 1.0)) #==> '#ffffff'
需要注意的是,颜色中的rgb值假定介于0.0和1.0之间.如果你想要在0到255之间,你需要做一个小转换.特别,
def hex_to_rgb(hex_string): rgb = colors.hex2color(hex_string) return tuple([int(255*x) for x in rgb]) def rgb_to_hex(rgb_tuple): return colors.rgb2hex([1.0*x/255 for x in rgb_tuple])
另一个注意事项是colors.hex2color
只接受有效的十六进制颜色字符串.
真的很快:
int r = ( hexcolor >> 16 ) & 0xFF; int g = ( hexcolor >> 8 ) & 0xFF; int b = hexcolor & 0xFF; int hexcolor = (r << 16) + (g << 8) + b;
真正的答案:取决于你正在寻找什么样的十六进制颜色值(例如565,555,888,8888等),alpha位的数量,实际颜色分布(rgb vs bgr ......)和一吨其他变量.
这是使用C++模板(直接来自ScummVM)的大多数RGB值的通用算法.
templateuint32 RGBToColor(uint8 r, uint8 g, uint8 b) { return T::kAlphaMask | (((r << T::kRedShift) >> (8 - T::kRedBits)) & T::kRedMask) | (((g << T::kGreenShift) >> (8 - T::kGreenBits)) & T::kGreenMask) | (((b << T::kBlueShift) >> (8 - T::kBlueBits)) & T::kBlueMask); }
这是565的示例颜色结构(16位颜色的标准格式):
template<> struct ColorMasks<565> { enum { highBits = 0xF7DEF7DE, lowBits = 0x08210821, qhighBits = 0xE79CE79C, qlowBits = 0x18631863, kBytesPerPixel = 2, kAlphaBits = 0, kRedBits = 5, kGreenBits = 6, kBlueBits = 5, kAlphaShift = kRedBits+kGreenBits+kBlueBits, kRedShift = kGreenBits+kBlueBits, kGreenShift = kBlueBits, kBlueShift = 0, kAlphaMask = ((1 << kAlphaBits) - 1) << kAlphaShift, kRedMask = ((1 << kRedBits) - 1) << kRedShift, kGreenMask = ((1 << kGreenBits) - 1) << kGreenShift, kBlueMask = ((1 << kBlueBits) - 1) << kBlueShift, kRedBlueMask = kRedMask | kBlueMask }; };
修改Jeremy的python答案来处理短的CSS rgb值,如0,#999和#fff(哪些浏览器会渲染为黑色,中灰色和白色):
def hex_to_rgb(value): value = value.lstrip('#') lv = len(value) if lv == 1: v = int(value, 16)*17 return v, v, v if lv == 3: return tuple(int(value[i:i+1], 16)*17 for i in range(0, 3)) return tuple(int(value[i:i+lv/3], 16) for i in range(0, lv, lv/3))