Benny H.
Benny H.

Reputation: 449

Generate Color Spectrum using Python

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 Image

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

Are there any existing working solutions available?

Upvotes: 3

Views: 9871

Answers (1)

Benny H.
Benny H.

Reputation: 449

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

Upvotes: 3

Related Questions