python生成渐变图
有时候设计图会有一些渐变,但是用代码不好实现,此时又不想麻烦设计同事,可用此脚本生成渐变图片
from PIL import Image, ImageDraw
def hex_to_rgb(hex_color):
# 将16进制颜色转换为RGB
return tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))
def create_gradient_image(width, height, color1, color2, direction):
# 创建一个新的图像
image = Image.new('RGB', (width, height))
draw = ImageDraw.Draw(image)
if direction == 'horizontal':
# 水平渐变
for x in range(width):
r = int(color1[0] + (color2[0] - color1[0]) * (x / width))
g = int(color1[1] + (color2[1] - color1[1]) * (x / width))
b = int(color1[2] + (color2[2] - color1[2]) * (x / width))
draw.line([(x, 0), (x, height)], fill=(r, g, b))
elif direction == 'vertical':
# 垂直渐变
for y in range(height):
r = int(color1[0] + (color2[0] - color1[0]) * (y / height))
g = int(color1[1] + (color2[1] - color1[1]) * (y / height))
b = int(color1[2] + (color2[2] - color1[2]) * (y / height))
draw.line([(0, y), (width, y)], fill=(r, g, b))
return image
def main():
# 提示用户输入
width = int(input("请输入图片宽度: "))
height = int(input("请输入图片高度: "))
color1_hex = input("请输入第一个颜色 (16进制, 例如 #FF0000): ").lstrip('#')
color2_hex = input("请输入第二个颜色 (16进制, 例如 #0000FF): ").lstrip('#')
direction = input("请输入渐变方向 (horizontal 或 vertical): ")
# 将16进制颜色转换为RGB
color1 = hex_to_rgb(color1_hex)
color2 = hex_to_rgb(color2_hex)
# 生成渐变图片
gradient_image = create_gradient_image(width, height, color1, color2, direction)
# 保存图片
gradient_image.save('gradient.png')
# 显示图片
gradient_image.show()
if __name__ == "__main__":
main()
发表回复