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

yipeiwu_com5年前Python基础

本文实例讲述了python以环状形式组合排列图片并输出的方法。分享给大家供大家参考。具体分析如下:

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

具体代码如下:

复制代码 代码如下:
# -*- coding: utf-8 -*-
__author__ = 'www.jb51.net'
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)
    )
    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))
        #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个 50x50 的pngs 图片,使用了绝对路径,需要自己进行替换成你的图片路径
imageFilenames = ["d:/www.jb51.net/images/1.png", "d:/www.jb51.net/images/2.png", "d:/www.jb51.net/images/3.png"] * 5
images = [Image.open(filename) for filename in imageFilenames]
arrangeImagesInCircle(img, images)
img.save("output.png")

希望本文所述对大家的Python程序设计有所帮助。

相关文章

python正则中最短匹配实现代码

python正则中最短匹配实现代码

下面从一个例子入手: 利用正则表达式解析下面的XML/HTML标签: <composer>Wolfgang Amadeus Mozart</composer>...

详解Python中的__new__、__init__、__call__三个特殊方法

__new__: 对象的创建,是一个静态方法,第一个参数是cls。(想想也是,不可能是self,对象还没创建,哪来的self) __init__ : 对象的初始化, 是一个实例方法,第一...

django celery redis使用具体实践

django celery redis使用具体实践

环境准备 python3.5.4 windows redis pip install celery pip install redis windows下启动redir...

IntelliJ IDEA安装运行python插件方法

IntelliJ IDEA安装运行python插件方法

IDEA 工具是我们常用的开发工具,全称:IntelliJ IDEA,它的功能强大就在于我们可以添加各种插件来编写不同的代码,当然也可以用来编写python,这篇文章我们来讲解,如何用I...

浅谈PyQt5中异步刷新UI和Python多线程总结

目前任务需要做一个界面程序,PyQt是非常方便的选择,QT丰富的控件以及python方便的编程。近期遇到界面中执行一些后台任务时界面卡死的情况,解决了在这里记录下。 PyQt PyQt简...