目的
色をRGBではなくてHSVで指定したいので、それ用の関数を作ってみました。
値の取れる範囲は、色々な表し方があると思いますが、以下で考えています。
- R, G, B, A: [0, 255]
- H: [0, 359]
- S, V, A: [0.0, 1.0]
切り上げや切り捨てを調整する必要があると思います。
環境
Python 3.14.2 (tags/v3.14.2:df79316, Dec 5 2025, 17:18:21) [MSC v.1944 64 bit (AMD64)]
コード
import colorsys
import math
def toRatio(n, base=255.0):
return n / base
def toValue(n, base=255.0):
return n * base
LengthRGBA = 8
def strToRgb(string):
s = string[1:] if string[0] == "#" else string
rgb = (int(s[:2], 16), int(s[2:4], 16), int(s[4:6], 16))
a = int(s[6:8], 16) if len(s) == LengthRGBA else None
return rgb, a
def rgbToHsv(rgb, a=None):
rgb = [toRatio(x) for x in rgb]
if a is not None:
a = toRatio(a)
hsv = list(colorsys.rgb_to_hsv(*rgb))
hsv[0] = toValue(hsv[0], 360)
return hsv, a
def hsvToRgb(hsv, a=None):
hsv[0] = toRatio(hsv[0], 360)
rgb = [math.ceil(toValue(x)) for x in colorsys.hsv_to_rgb(*hsv)]
if a is not None:
a = math.ceil(toValue(a))
return rgb, a
def rgbToString(rgb, a=None):
string = "#" + "".join([f"{math.ceil(x):02X}" for x in rgb])
if a is not None:
a = f"{math.ceil(a):X}"
string += a
return string
def test(s):
c, a = strToRgb(s)
print(c, a)
c, a = rgbToHsv(c, a)
print(c, a)
c, a = hsvToRgb(c, a)
print(c, a)
c = rgbToString(c, a)
print(c)
if __name__ == "__main__":
s = "#EE1122"
test(s)
s = "#AB124450"
test(s)
s = "#EE00FF"
test(s)
実行結果
[238, 17, 34] None
[355.3846153846154, 0.9285714285714286, 0.9333333333333333] None
[238, 17, 34] None
#EE1122
[171, 18, 68] 80
[340.39215686274514, 0.8947368421052632, 0.6705882352941176] 0.3137254901960784
[171, 18, 68] 80
#AB124450
[238, 0, 255] None
[296.0, 1.0, 1.0] None
[239, 0, 255] None
#EF00FF