Converting hex color to RGB and vice-versa

2019-01-04 21:56发布

What is the most efficient way to do this?

标签: colors hex rgb
9条回答
2楼-- · 2019-01-04 22:19

Modifying Jeremy's python answer to handle short CSS rgb values like 0, #999, and #fff (which browsers would render as black, medium grey, and white):

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))
查看更多
可以哭但决不认输i
3楼-- · 2019-01-04 22:20

Real answer: Depends on what kind of hexadecimal color value you are looking for (e.g. 565, 555, 888, 8888, etc), the amount of alpha bits, the actual color distribution (rgb vs bgr...) and a ton of other variables.

Here's a generic algorithm for most RGB values using C++ templates (straight from ScummVM).

template<class T>
uint32 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);
}

Here's a sample color struct for 565 (the standard format for 16 bit colors):

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

};
};
查看更多
家丑人穷心不美
4楼-- · 2019-01-04 22:20
#!/usr/bin/env python

import re
import sys

def hex_to_rgb(value):
  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(rgb):
  rgb = eval(rgb)
  r = rgb[0]
  g = rgb[1]
  b = rgb[2]
  return '#%02X%02X%02X' % (r,g,b)

def main():
  color = raw_input("HEX [#FFFFFF] or RGB [255, 255, 255] value (no value quits program): ")
  while color:
    if re.search('\#[a-fA-F0-9][a-fA-F0-9][a-fA-F0-9][a-fA-F0-9][a-fA-F0-9][a-fA-F0-9]', color):
      converted = hex_to_rgb(color)
      print converted
    elif re.search('[0-9]{1,3}, [0-9]{1,3}, [0-9]{1,3}', color):
      converted = rgb_to_hex(color)
      print converted
    elif color == '':
      sys.exit(0)
    else:
      print 'You didn\'t enter a valid value!'
    color = raw_input("HEX [#FFFFFF] or RGB [255, 255, 255] value (no value quits program): ")

if __name__ == '__main__':
  main()
查看更多
该账号已被封号
5楼-- · 2019-01-04 22:23

just real quick:

int r = ( hexcolor >> 16 ) & 0xFF;

int g = ( hexcolor >> 8 ) & 0xFF;

int b = hexcolor & 0xFF;

int hexcolor = (r << 16) + (g << 8) + b;
查看更多
Juvenile、少年°
6楼-- · 2019-01-04 22:23

A hex value is just RGB numbers represented in hexadecimal. So you just have to take each pair of hex digits and convert them to decimal.

Example:

#FF6400 = RGB(0xFF, 0x64, 0x00) = RGB(255, 100, 0)
查看更多
劳资没心,怎么记你
7楼-- · 2019-01-04 22:29

In 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'
查看更多
登录 后发表回答