使用Python生成颜色光谱

3
我想生成一个类似这样的颜色谱图像: enter image description here 作为 png 图片。但图片的宽度和高度应该是可调整的。颜色应该使用十六进制值,就像 HTML 颜色代码一样(例如 #FF0000)。
我知道如何进行比例缩放,但我认为已经有解决方案可以计算蓝色到红色的升级,然后向下计数红色等,在分辨率下获得所需的图片宽度。
为了生成图片,我想到了 PIL(Python Imaging Library)。
from PIL import Image

im = Image.new("RGB", (width, height))
im.putdata(DEC_tuples)
im.save("Picture", "PNG")

是否有任何现有的可行解决方案?

1个回答

3

我自己想到了一个解决办法,效果还不错。生成的图片会自动变成一个新的宽度,因为我不会生成小数。

from PIL import Image

width = 300 # Expected Width of generated Image
height = 100 # Height of generated Image

specratio = 255*6 / width

print ("SpecRatio: " + str(specratio))

red = 255
green = 0
blue = 0

colors = []

step = round(specratio)

for u in range (0, height):
    for i in range (0, 255*6+1, step):
        if i > 0 and i <= 255:
            blue += step
        elif i > 255 and i <= 255*2:
            red -= step
        elif i > 255*2 and i <= 255*3:
            green += step
        elif i > 255*3 and i <= 255*4:
            blue -= step
        elif i > 255*4 and i <= 255*5:
            red += step
        elif i > 255*5 and i <= 255*6:
            green -= step

        colors.append((red, green, blue))

newwidth = int(i/step+1) # Generated Width of Image without producing Float-Numbers

print (str(colors))


im = Image.new("RGB", (newwidth, height))
im.putdata(colors)
im.save("Picture", "PNG")

谢谢。我从来没有想过使用“putdata”。 - hyankov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接