Python – Generate Color Spectrum using Python

colors, image-processing, pillow, python, python-imaging-library

I want to generate a color spectrum like that:
enter image description here

as a png picture. But the width and height of the picture should be adjustable. The Colors should be used as hex values like the HTML Color-Code (for example #FF0000).

I know how the scale works but i think there are already any solutions how to count up the blue to red, then counting down red etc. in a resolution that acquires the needed width of the picture.

For generating the Picture i thought about PIL:

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

Are there any existing working solutions available?

Best Solution

Found a solution by myself and it works pretty well, the generated image will become a new width because I won't generate float-numbers.

from PIL import Imagewidth = 300 # Expected Width of generated Imageheight = 100 # Height of generated Imagespecratio = 255*6 / widthprint ("SpecRatio: " + str(specratio))red = 255green = 0blue = 0colors = []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-Numbersprint (str(colors))im = Image.new("RGB", (newwidth, height))im.putdata(colors)im.save("Picture", "PNG")