玩蛇网提供最新Python编程技术信息以及Python资源下载!

Python实现HTML颜色和RGB颜色互转的方法

python 培训

本文是关于Python实现HTML颜色和RGB颜色互转的方法,提供源码参考。在网上有看到过RGB颜色值转换成十六进制颜色码的工具,感觉不错,自己也试着也了一个类似的HTML颜色和RGB颜色互转的Python方法的实现。

Python HTML颜色和RGB颜色互转

Python实现HTML颜色和RGB颜色互转的方法,python源码如下:

#coding=utf-8

def RGBToHTMLColor(rgb_tuple):
    """ convert an (R, G, B) tuple to #RRGGBB """

    hexcolor = '#%02x%02x%02x' % rgb_tuple

    # that's it! '%02x' means zero-padded, 2-digit hex values

    return hexcolor

def HTMLColorToRGB(colorstring):
    """ convert #RRGGBB to an (R, G, B) tuple """

    colorstring = colorstring.strip()

    if colorstring[0] == '#': colorstring = colorstring[1:]

    if len(colorstring) != 6:
        raise ValueError, "input #%s is not in #RRGGBB format" % colorstring

    r, g, b = colorstring[:2], colorstring[2:4], colorstring[4:]
    r, g, b = [int(n, 16) for n in (r, g, b)]

    return (r, g, b)

def HTMLColorToPILColor(colorstring):
    """ converts #RRGGBB to PIL-compatible integers"""

    colorstring = colorstring.strip()

    while colorstring[0] == '#': colorstring = colorstring[1:]
    # get bytes in reverse order to deal with PIL quirk
    colorstring = colorstring[-2:] + colorstring[2:4] + colorstring[:2]
    # finally, make it numeric
    color = int(colorstring, 16)

    return color

def PILColorToRGB(pil_color):
    """ convert a PIL-compatible integer into an (r, g, b) tuple """

    hexstr = '%06x' % pil_color
    # reverse byte order
    r, g, b = hexstr[4:], hexstr[2:4], hexstr[:2]
    r, g, b = [int(n, 16) for n in (r, g, b)]

    return (r, g, b)

def PILColorToHTMLColor(pil_integer):
    return RGBToHTMLColor(PILColorToRGB(pil_integer))

def RGBToPILColor(rgb_tuple):
    return HTMLColorToPILColor(RGBToHTMLColor(rgb_tuple))

#www.iplaypython.com

import Image

def getRGBTupleFromImg(file_obj, coords=(0,0)):
    """ 
    Extract an #RRGGBB color string from given pixel coordinates
    in the given file-like object.
    """
    pil_img = Image.open(file_obj)
    pil_img = pil_img.convert('RGB')
    rgb = pil_img.getpixel(coords)
    return rgb

if __name__ == '__main__':
    htmlcolor = '#ff00cc'

    pilcolor = HTMLColorToPILColor(htmlcolor)

    rgb = HTMLColorToRGB(htmlcolor)

    print pilcolor
 
   print htmlcolor

    print rgb

    print PILColorToHTMLColor(pilcolor)

    print PILColorToRGB(pilcolor)

    print RGBToPILColor(rgb)

    print RGBToHTMLColor(rgb)

    print
 
   img = open('/tmp/bkg.gif', 'r')
 
   print getRGBTupleFromImg(img, (0,0))

玩蛇网原创,转载请注明文章出处和来源网址:http://www.iplaypython.com/code/other/o2601.html



微信公众号搜索"玩蛇网Python之家"加关注,每日最新的Python资讯、图文视频教程可以让你一手全掌握。强烈推荐关注!

微信扫描下图可直接关注

玩蛇网Python新手QQ群,欢迎加入: ① 240764603 玩蛇网Python新手群
文章发布日期:2016-01-11 16:01 玩蛇网 www.iplaypython.com

评论列表(网友评论仅供网友表达个人看法,并不表明本站同意其观点或证实其描述)
相关文章推荐
别人正在看
特别推荐
去顶部去底部