Draw Gradient

It’s easy to create a gradient like this in Python:

Code:

from PIL import Image
gradient = Image.new('L', (256, 256), 0)
pix = gradient.load()
for x in range(256):
    for y in range(256):
        # pix[x,y] = x            # horizontal
        # pix[x,y] = 255-x        # backwards
        # pix[x,y] = y            # vertical
        # pix[x,y] = (x + y)//2   # diagonal
gradient.save('gradient.png')

Here’s what the code does:
1) Create a new 256 x 256 image in “L” mode.

This size is convenient, because we can start with a lightness of 0 in the first column and count up by 1’s until we reach a lightness of 255 in the last column. The image is “L” mode (grayscale / monochrome), because that can be used directly as a mask in Python’s PIL.

See Alpha Mask Gradients for examples of how this can be used.

2) Loop through every pixels (x, y coordinates) and set the lightness (“L”) value according to those variables.

Select one of the commented out lines to pick a gradient direction. The simplest is something like “lightness = x” which makes the lightness count up as the x value counts up, resulting in a horizontal gradient.