Two-color linear gradient positioning with PIL Python

Viewed 665

Perhaps it is something easy for many. I am trying to create a background from 2 colors. The intention is that it starts on the left with one color and ends with another color on its right side (horizontally.)

the question is that I have from corner to corner. and what I'm looking for is that it is side by side.

My code:

from PIL import Image, ImageDraw

def interpolate(f_co, t_co, interval):
    det_co =[(t - f) / interval for f , t in zip(f_co, t_co)]
    for i in range(interval):
        yield [round(f + det * i) for f, det in zip(f_co, det_co)]


imgsize=(1920,1080)
gradient = Image.new('RGBA', imgsize, color=0)
draw = ImageDraw.Draw(gradient)

f_co = (253, 46, 216)
t_co = (23, 214, 255)
for i, color in enumerate(interpolate(f_co, t_co, gradient.width * 2)):
    draw.line([(i, 0), (0, i)], tuple(color), width=1)
gradient.show()

result: https://i.imgur.com/p5slKTg.png

2 Answers

For left to right, the easiest fix is to just modify the draw.line coordinates from

draw.line([(i, 0), (0, i)], tuple(color), width=1)

to

draw.line([(i, 0), (i, gradient.height)], tuple(color), width=1)

and adjust gradient.width * 2 in the interpolate() call to just gradient.width. The result is

enter image description here

For top to bottom, you'll need to adjust the argument to interpolate() to use gradient.height and do

draw.line([(0, i), (gradient.width, i)], tuple(color), width=1)

and the result is enter image description here

I think I would take a different approach rather than drawing 3,840 lines:

#!/usr/bin/env python3

import numpy as np
from PIL import Image

# Define start and end colours and image height and width
colourA=[255, 0, 255]
colourB=[0, 255, 255]
h, w = 1080, 1920

# Make output image
gradient = np.zeros((h,w,3), np.uint8)

# Fill R, G and B channels with linear gradient between two end colours
gradient[:,:,0] = np.linspace(colourA[0], colourB[0], w, dtype=np.uint8)
gradient[:,:,1] = np.linspace(colourA[1], colourB[1], w, dtype=np.uint8)
gradient[:,:,2] = np.linspace(colourA[2], colourB[2], w, dtype=np.uint8)

# Save result
Image.fromarray(gradient).save('result.png')

enter image description here

Related