More details on Image.linear_gradient #6276
-
|
Since Andrew so kindly answered my previous question about a progress bar, I am trying to learn more about linear_gradient. The docs seem a bit bland and bare - am I looking in the right place? What is "mode"? What are the range of values? Or maybe this is common knowledge and I simply missing it. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
|
For information about mode, see https://pillow.readthedocs.io/en/latest/handbook/concepts.html#modes
To generate a horizontal gradient from red to yellow in my previous example,
That was just me putting together a quick example. If you want to create a more complex linear gradient, it would probably be simpler to use from PIL import Image
def gradient(size, start, stop):
im = Image.new("RGB", size)
for x in range(im.width):
progress = x / (im.width - 1)
color = tuple(int(start[i] * (1 - progress) + stop[i] * progress) for i in range(3))
for y in range(im.height):
im.putpixel((x, y), color)
return im
im = gradient((256, 50), (255, 0, 0), (255, 255, 0))
im.show() |
Beta Was this translation helpful? Give feedback.
-
|
I used this snippet with some alterations. If you also want to take alpha (transparency) into account, make it an RGBA Image and change from PIL import Image
def gradient(size, start, stop):
im = Image.new("RGBA", size)
for y in range(im.height):
progress = y / (im.height - 1)
color = tuple(int(start[i] * (1 - progress) + stop[i] * progress) for i in range(4))
for x in range(im.width):
im.putpixel((x, y), color)
return im
im = gradient((50, 256), (255, 0, 0, 20), (255, 255, 0, 255))
im.show() |
Beta Was this translation helpful? Give feedback.
For information about mode, see https://pillow.readthedocs.io/en/latest/handbook/concepts.html#modes
linear_gradientis not a very flexible function. When the docs say "Generate 256x256 linear gradient from black to white, top to bottom.", that's not just the default functionality, that's the entire functionality.To generate a horizontal gradient from red to yellow in my previous example,
merge()to have a solid red channel, treat the gradient as the green channel, and an empty blue channel. That meant that the gradient went from full re…