在 Python 中将十六进制转换为 RGB 值 [英] Converting Hex to RGB value in Python

查看:95
本文介绍了在 Python 中将十六进制转换为 RGB 值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里解决 Jeremy 的回复:将十六进制颜色转换为 RGB 和副-相反我能够得到一个python程序来转换预设的颜色十六进制代码(例如#B4FBB8),但是从最终用户的角度来看,我们不能要求人们编辑代码&从那里跑.如何提示用户输入一个十六进制值,然后让它从那里吐出一个 RGB 值?

Working off Jeremy's response here: Converting hex color to RGB and vice-versa I was able to get a python program to convert preset colour hex codes (example #B4FBB8), however from an end-user perspective we can't ask people to edit code & run from there. How can one prompt the user to enter a hex value and then have it spit out a RGB value from there?

这是我迄今为止的代码:

Here's the code I have thus far:

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):
    return '#%02x%02x%02x' % rgb

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'

print('Please enter your colour hex')

hex == input("")

print('Calculating...')
print(hex_to_rgb(hex()))

使用行 print(hex_to_rgb('#B4FBB8')) 我能够让它吐出正确的 RGB 值,即 (180, 251, 184)

Using the line print(hex_to_rgb('#B4FBB8')) I'm able to get it to spit out the correct RGB value which is (180, 251, 184)

这可能非常简单 - 我对 Python 的使用仍然很粗糙.

It's probably super simple - I'm still pretty rough with Python.

推荐答案

我相信这可以满足您的需求:

I believe that this does what you are looking for:

h = input('Enter hex: ').lstrip('#')
print('RGB =', tuple(int(h[i:i+2], 16) for i in (0, 2, 4)))

(以上是为 Python 3 编写的)

(The above was written for Python 3)

样品运行:

Enter hex: #B4FBB8
RGB = (180, 251, 184)

写入文件

要写入带有句柄 fhandle 的文件,同时保留格式:

Writing to a file

To write to a file with handle fhandle while preserving the formatting:

fhandle.write('RGB = {}'.format( tuple(int(h[i:i+2], 16) for i in (0, 2, 4)) ))

这篇关于在 Python 中将十六进制转换为 RGB 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆