Python implements the function of converting colors RGB and hex to each other

  • 2020-04-02 14:44:19
  • OfStack

This article illustrates a python function that converts colors from RGB to hex. Share with you for your reference. Specific analysis is as follows:

The python code below provides two functions to convert the RGB color to the hex value, hex to the RGB, which is a primitive of three Numbers, such as (128,255,28) and hex to the number 876645


def hex2rgb(hexcolor):
  rgb = [(hexcolor >> 16) & 0xff,
      (hexcolor >> 8) & 0xff,
      hexcolor & 0xff
     ]
  return rgb
def rgb2hex(rgbcolor):
  r, g, b = rgbcolor
  return (r << 16) + (g << 8) + b

Call method:


print("www.jb51.net rgb2hex((128,128,18))=%s"%rgb2hex((128,128,18)))
print("www.jb51.net rgb2hex(8421394)=%s"%hex2rgb(8421394))

The output results are as follows:


www.jb51.net rgb2hex((128,128,18))=8421394
www.jb51.net rgb2hex(8421394)=[128, 128, 18]

I hope this article has helped you with your Python programming.


Related articles: