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开发常用的一些开源Package分享

一般安装完Python后,我会先装一些常用的Package。做个笔记,记录下来,以备查询: Web FrameWorks Tornado,访问:http://www.tornadoweb...

python基于隐马尔可夫模型实现中文拼音输入

python基于隐马尔可夫模型实现中文拼音输入

在网上看到一篇关于隐马尔科夫模型的介绍,觉得简直不能再神奇,又在网上找到大神的一篇关于如何用隐马尔可夫模型实现中文拼音输入的博客,无奈大神没给可以运行的代码,只能纯手动网上找到了结巴分词...

PyQt5重写QComboBox的鼠标点击事件方法

最近学PyQt5,想要做一个串口调试助手来练练手,之前用了正点原子的串口上位机,觉得点击ComboBox自动检测串口这个功能很棒,之前用QT5写串口调试助手的时候也想加入这个功能,但是一...

如何基于python实现画不同品种的樱花树

如何基于python实现画不同品种的樱花树

这篇文章主要介绍了如何基于python实现画不同品种的樱花树,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下  动态生成樱花...

对python捕获ctrl+c手工中断程序的两种方法详解

日常编写调试运行程序过程中,难免需要手动停止,以下两种方法可以捕获ctrl+c立即停止程序 1、使用python的异常KeyboardInterrupt try: whi...