python PIL 生成随机形状
时间: 2023-07-04 14:09:21 浏览: 128
python基于PIL生成四位随机图形验证码
你可以使用Python的PIL库(Python Imaging Library)来生成随机形状。下面是一个简单的示例代码,可以生成随机的圆形、矩形和椭圆形:
```python
from PIL import Image, ImageDraw
import random
# 生成随机形状
def random_shape(width, height):
# 创建一个空白图像
img = Image.new("RGBA", (width, height), (255, 255, 255, 0))
draw = ImageDraw.Draw(img)
# 随机选择形状类型
shape_type = random.choice(["circle", "rectangle", "ellipse"])
# 随机生成形状的位置和大小
x1 = random.randint(0, width)
y1 = random.randint(0, height)
x2 = random.randint(0, width)
y2 = random.randint(0, height)
size = random.randint(20, 100)
# 根据形状类型绘制形状
if shape_type == "circle":
draw.ellipse((x1, y1, x1 + size, y1 + size), fill=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255), 255))
elif shape_type == "rectangle":
draw.rectangle((x1, y1, x1 + size, y1 + size), fill=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255), 255))
else:
draw.ellipse((x1, y1, x2, y2), fill=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255), 255))
return img
# 生成多个随机形状
def generate_shapes(num_shapes, width, height):
result = Image.new("RGBA", (width, height), (255, 255, 255, 0))
for i in range(num_shapes):
img = random_shape(width, height)
result = Image.alpha_composite(result, img)
return result
# 测试
img = generate_shapes(10, 500, 500)
img.show()
```
这个示例代码会生成一个500x500的图像,其中包含10个随机形状。你可以根据自己的需求修改参数来生成不同大小和数量的随机形状。
阅读全文