Python 生成随机颜色图片并合并:300x300图片示例
以下是 Python 代码实现:
import random
from PIL import Image
# 生成随机颜色
def random_color():
return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
# 生成随机颜色的图片
def generate_image():
color = random_color()
img = Image.new('RGB', (300, 300), color)
return img
# 生成10个随机颜色的图片
images = []
for i in range(10):
img = generate_image()
images.append(img)
# 合并图片
width, height = images[0].size
result_img = Image.new('RGB', (width * 10, height))
for i in range(10):
result_img.paste(images[i], (i * width, 0))
# 保存图片
result_img.save('random_colors.jpg')
这段代码首先定义了一个random_color函数,用于生成随机颜色;然后定义了一个generate_image函数,用于生成随机颜色的300x300图片;接着使用for循环生成10个随机颜色的图片,并将它们保存在一个列表中;最后使用Image模块中的new函数创建一个空白的宽度为10个图片宽度,高度为单个图片高度的图片,然后使用paste函数将10个随机颜色的图片合并到一起,最后保存到本地目录中。
原文地址: https://www.cveoy.top/t/topic/mNFI 著作权归作者所有。请勿转载和采集!