本文实例讲述了python以环状形式组合排列图片并输出的方法。分享给大家供大家参考。具体分析如下:
这段代码可以自定义一个空白画板,然后将指定的图片以圆环状的方式排列起来,用到了pil库,可以通过:
pip install pil 的方式安装。
具体代码如下:
# -*- coding: utf-8 -*-<br />__author__ = 'www.gaodaima.com'<br />import math<br />from PIL import Image<br />def arrangeImagesInCircle(masterImage, imagesToArrange):<br /> imgWidth, imgHeight = masterImage.size<br /> #we want the circle to be as large as possible.<br /> #but the circle shouldn't extend all the way to the edge of the image.<br /> #If we do that, then when we paste images onto the circle, those images will partially fall over the edge.<br /> #so we reduce the diameter of the circle by the width/height of the widest/tallest image.<br /> diameter = min(<br /> imgWidth - max(img.size[0] for img in imagesToArrange),<br /> imgHeight - max(img.size[1] for img in imagesToArrange)<br /> )<br /> radius = diameter / 2<br /> circleCenterX = imgWidth / 2<br /> circleCenterY = imgHeight / 2<br /> theta = 2*math.pi / len(imagesToArrange)<br /> for i in range(len(imagesToArrange)):<br /> curImg = imagesToArrange[i]<br /> angle = i * theta<br /> dx = int(radius * math.cos(angle))<br /> dy = int(radius * math.sin(angle))<br /> #dx and dy give the coordinates of wh<div>本文来源gaodai.ma#com搞#代!码网_</div>ere the center of our images would go.<br /> #so we must subtract half the height/width of the image to find where their top-left corners should be.<br /> pos = (<br /> circleCenterX + dx - curImg.size[0]/2,<br /> circleCenterY + dy - curImg.size[1]/2<br /> )<br /> masterImage.paste(curImg, pos)<br />img = Image.new("RGB", (500,500), (255,255,255))<br />#下面的三个图片是3个 50x50 的pngs 图片,使用了绝对路径,需要自己进行替换成你的图片路径<br />imageFilenames = ["d:/www.gaodaima.com/images/1.png", "d:/www.gaodaima.com/images/2.png", "d:/www.gaodaima.com/images/3.png"] * 5<br />images = [Image.open(filename) for filename in imageFilenames]<br />arrangeImagesInCircle(img, images)<br />img.save("output.png")
希望本文所述对大家的Python程序设计有所帮助。