Skip to main content
 首页 » 编程设计

python之使用 Python 生成色谱

2025年02月15日11kenshinobiy

我想生成这样的色谱:

作为png图片。但是图片的宽度和高度应该是可调的。颜色应用作十六进制值,如 HTML 颜色代码(例如 #FF0000)。

我知道比例是如何工作的,但我认为已经有任何解决方案如何在获得所需图片宽度的分辨率下从蓝色到红色计数,然后从红色开始计数等等。

为了生成图片,我想到了 PIL:

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

是否有可用的现有工作解决方案?

请您参考如下方法:

自己找到了一个解决方案,效果很好,生成的图像会变成新的宽度,因为我不会生成 float 。

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")