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

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

WBOY
Release: 2016-06-10 15:17:09
Original
2554 people have browsed it

本文实例讲述了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
Copy after login

调用方法:

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

输出结果如下:

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

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template