我制作了一个小脚本来使用 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")
但是,我没有使用渐变,而是使用纯色(蓝色)和顶部的一条细小的红色线。有办法解决吗?
最佳答案
您可能会发现使用内置的 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))
关于python - 使用PIL的渐变只是一种纯色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75998474/