Home >Backend Development >Python Tutorial >python实现颜色rgb和hex相互转换的函数

python实现颜色rgb和hex相互转换的函数

WBOY
WBOYOriginal
2016-06-10 15:17:092554browse

本文实例讲述了python实现颜色rgb和hex相互转换的函数。分享给大家供大家参考。具体分析如下:

下面的python代码提供了两个函数分别用来将rgb表示的颜色转换成hex值,hex转换成rgb,rgb为一个三个数的元祖,如(128,255,28),hex为数字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

调用方法:

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

输出结果如下:

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

希望本文所述对大家的Python程序设计有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn