python - 使用PIL的渐变只是一种纯色

标签 python image python-imaging-library gradient

我制作了一个小脚本来使用 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))

enter image description here

关于python - 使用PIL的渐变只是一种纯色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75998474/

相关文章:

python - cuBLAS Dgemm 产品与 python

python - 在 Python 中使用 XPath 和 ETXPath 的 LXML

xcode - 在 Xcode 项目中添加图像时出现黑色背景

javascript - 尝试使用 css 将图像添加到 SVG 圆

Python 图像库,ImageFont IOError

python - 删除 Python 字符串中的第一个单词?

python - numpy 将向量转换为二进制矩阵

javascript - 如何在图像中添加全尺寸弹出框?

python - OS X 10.7 Lion 升级后无法编译 PIL/pysqlite

python - 使用 Python 图像库模糊包含文本的图像