# python以环状形式组合排列图片并输出的方法

pip install pil 的方式安装。

# -*- coding: utf-8 -*-
__author__ = ‘www.bitscn.com’
import math
from pil import image
def arrangeimagesincircle(masterimage, imagestoarrange):
imgwidth, imgheight = masterimage.size
#we want the circle to be as large as possible.
#but the circle shouldn’t extend all the way to the edge of the image.
#if we do that, then when we paste images onto the circle, those images will partially fall over the edge.
#so we reduce the diameter of the circle by the width/height of the widest/tallest image.
diameter = min(
imgwidth – max(img.size[0] for img in imagestoarrange),
imgheight – max(img.size[1] for img in imagestoarrange)
)
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 and dy give the coordinates of where the center of our images would go.
#so we must subtract half the height/width of the image to find where their top-left corners should be.
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个 50×50 的pngs 图片，使用了绝对路径，需要自己进行替换成你的图片路径
imagefilenames = [“d:/www.bitscn.com/images/1.png”, “d:/www.bitscn.com/images/2.png”, “d:/www.bitscn.com/images/3.png”] * 5
images = [image.open(filename) for filename in imagefilenames]
arrangeimagesincircle(img, images)
img.save(“output.png”)

Posted in 未分类