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

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

问题描述

在这里处理Jeremy的回复:将十六进制颜色转换为RGB,反之亦然-versa 我能够获得一个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中将Hex转换为RGB值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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