python以环状形式组合排列图片并输出

2022-05-03 00:00:00 组合 排列 环状

这段代码可以自定义一个空白画板,然后将指定的图片以圆环状的方式排列起来,用到了pil库,可以通过:
pip install pil 的方式安装。

"""
皮蛋编程(https://www.pidancode.com)
创建日期:2022/3/31
功能描述:python以环状形式组合排列图片并输出
"""

import math
from PIL import Image


def arrangeImagesInCircle(masterImage, imagesToArrange):
    imgWidth, imgHeight = masterImage.size
    diameter = min(
        imgWidth - max(img.size[0] for img in imagesToArrange),
        imgHeight - max(img.size[1] for img in imagesToArrange)
    )
    radius = diameter / 2
    circleCenterX = imgWidth / 2
    circleCenterY = imgHeight / 2
    theta = 2 * math.pi / len(imagesToArrange)
    for i in range(len(imagesToArrange)):
        curImg = imagesToArrange[i]
        angle = i * theta
        dx = int(radius * math.cos(angle))
        dy = int(radius * math.sin(angle))
        pos = (
            circleCenterX + dx - curImg.size[0] / 2,
            circleCenterY + dy - curImg.size[1] / 2
        )
        masterImage.paste(curImg, pos)


img = Image.new("RGB", (500, 500), (255, 255, 255))
# 下面的三个图片是3个 50x50 的pngs 图片,使用了绝对路径,需要自己进行替换成你的图片路径
imageFilenames = ["./pidancode.com/images/1.png", "./pidancode.com/images/2.png", "./pidancode.com/images/3.png"] * 5
images = [Image.open(filename) for filename in imageFilenames]
arrangeImagesInCircle(img, images)
img.save("output.png")

相关文章