[英]How to convert a hexadecimal color value to RGB in Python
如何將十六進制顏色值(如#ff3ab4
)轉換為三元組RGB值(128, 255, 0)
如(128, 255, 0)
#ff3ab4
) (128, 255, 0)
?
省略前導零的原因是因為字符串被轉換為數字,並且當您再次嘗試將數字表示為字符串時,它不會顯示任何前導0,因為該數字沒有確定的長度,不知道它起源於一個字符串,而字符串確實具有一定的長度。
在您的情況下,我假設您想將單獨的A,R,B和G部分返回為格式正確的字符串。 如果要手動執行此操作,請執行以下操作:
def colorComponents(hexAsString):
def uniformLength(string):
return string[:2] + "".zfill(10-len(string)) + string[2:]
re = []
re.append(str(hex(int(hexAsString, 16) & int("0xFF000000", 16))))
re.append(str(hex(int(hexAsString, 16) & int("0x00FF0000", 16))))
re.append(str(hex(int(hexAsString, 16) & int("0x0000FF00", 16))))
re.append(str(hex(int(hexAsString, 16) & int("0x000000FF", 16))))
for i in range(len(re)):
re[i] = uniformLength(re[i])
return re
請注意,這絕不是以性能優化的方式。 :)您應該立即使用整數(例如使用255而不是int(“ 0xFF000000”,16))。 這樣,盡管您可以清楚地看到位掩碼im用於將單獨的組件過濾為十六進制數。
我相當確定還有諸如字符串格式化程序之類的功能,它們也可以將數字表示為漂亮的字符串,但我從未使用過它們,所以我無法告訴您這些解決方案的外觀如何:)
編輯:如果您不清楚我使用的位掩碼如何工作,這是一個(希望)簡單的示例:假設您有2個字節的數據以其位形式表示:
bytes0 = 0011 0101
bytes1 = 0000 1111
&
運算符是按位AND運算符。
bytesAND = bytes0 & bytes1
bytesAND
現在看起來像這樣:
0000 0101
>>> bit32_to_bytes = lambda x: [255 & (x >> 8 * i) for i in (0,1,2,3)]
>>> bit32_to_bytes(0xFFEE2200)
[0L, 34L, 238L, 255L]
一些解釋:
>>> bin(0xFF00)
'0b1111111100000000' # this is string, not a number
>>> bin(0xFF00 >> 8) # shift right by 8 bits
'0b11111111' # leading zeros striped
>>> bin(0xA0FF00)
'0b101000001111111100000000' # 24-bit number
>>> bin(0xA0FF00 >> 8) # shift by 1 byte (drop the lowest byte)
'0b000000001010000011111111' # leading zeros added by myself!
>>> bin(255 & (0xA0FF00 >> 8)) # shift right (by 1 byte) and mask (get last byte)
'0b000000000000000011111111' # leading zeros added by myself!
屏蔽y = 255 & x
, y
接收數字x
中的低字節值。 y = 255 & (x >> 8 * n)
-> y =從x開始的第n個字節
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.