PIL Image, ImageDrawfrom import
generate_jpg(width: , height: , output: ) :def int int str -> None
"""
生成一张随机的 JPG 图片
:param width: 生成的图片的宽度
:param height: 生成的图片的高度
:param output: 输出文件名称
"""
img: Image Image.new( , (width, height))= "RGB"
pixels img.load()=
x (width):for in range
y (height):for in range
r random.randint( , )= 0 255
g random.randint( , )= 0 255
b random.randint( , )= 0 255
pixels[x, y] (r, g, b)=
img.save(output, )format="JPEG"
( output stat(output) st_size )print f"the generated JPEG image is stored in { }, file size is {os. . / 1024} KB"
generate_png(width: , height: , output: ) :def int int str -> None
"""
生成一张随机的 PNG 图片
:param width: 生成的图片的宽度
:param height: 生成的图片的高度
:param output: 输出文件名称
"""
img: Image Image.new( , (width, height))= "RGBA"
draw: ImageDraw ImageDraw.Draw(img)=
x (width):for in range
y (height):for in range
alpha random.randint( , )= 0 255
r random.randint( , )= 0 255
g random.randint( , )= 0 255
b random.randint( , )= 0 255
draw.point((x, y), fill (r, g, b, alpha))=
img.save(output, )format="PNG"
( output stat(output) st_size )print f"the generated PNG image is stored in { }, file size is {os. . / 1024} KB"
generate_gif(width: , height: , num_frames: , output: ) :def int int int str -> None
"""
生成一张随机的 GIF 图片
:param width: 生成的图片的宽度
:param height: 生成的图片的高度
:param num_frames: 生成的图片的桢数
:param output: 输出文件名称
"""
frames: typing.List[Image] []=
_ (num_frames):for in range
# 生成每一帧的随机图像
image Image.new( , (width, height))= "RGB"
x (width):for in range
y (height):for in range
r random.randint( , )= 0 255
g random.randint( , )= 0 255
b random.randint( , )= 0 255
image.putpixel((x, y), (r, g, b))
# 将当前帧添加到帧列表中
frames.append(image)
# 保存图像
frames[ ]