我做了一个小脚本来使用 python 创建渐变并将其保存为图像。这是代码:
from PIL import Image, ImageDraw
# Define the image size and color gradient
width, height = 500, 500
color_start = (255, 0, 0) # red
color_end = (0, 0, 255) # blue
# Create a new image with the given size
image = Image.new("RGB", (width, height))
# Draw a gradient background on the image
draw = ImageDraw.Draw(image)
for y in range(height):
color = tuple(int(color_start[j] + (color_end[j] - color_start[j]) * y) for j in range(3))
draw.line((0, y, width, y), fill=color)
# Save the image to a PNG file
image.save("gradient.png")
但是,我没有使用渐变,而是使用纯色(蓝色)和顶部的一条红色细线。有办法解决这个问题吗?
那是因为你需要按
height
: color = tuple(int(color_start[j] + (color_end[j] - color_start[j]) * y / height) for j in range(3))
来划分。希望有帮助
与其绘制数百条线,您可能会发现使用内置的 linear_gradient() 函数更直观,它可以为您提供 256x256 的线性渐变:
from PIL import Image
# Generate Red, Green and Blue bands individually
G = Image.new('L', (256,256)) # 256x256, black, i.e. 0
B = Image.linear_gradient('L') # 256x256, black at top, white at bottom
R = B.rotate(180) # 256x256, white at top, black at bottom
# Merge and resize
grad = Image.merge("RGB",(R,G,B)).resize((512,512))