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中PDB模块中的命令来调试Python代码的教程

你有多少次陷入不得不更改别人代码的境地?如果你是一个开发团队的一员,那么你遇到上述境地的次数比你想要的还要多。然而,Python中有一个整洁的调试特性(像其他大多数语言一样),在这种情况...

在Python中等距取出一个数组其中n个数的实现方式

在Python中等距取出一个数组其中n个数的实现方式

应用场景: 实验中不断得到新数据,想将数据图形化,但随着时间推移,数据越来越多, 此时需要我们等距选择数据列表中固定数量的数据,来进行图形化。 注:保留首尾数据。 import nu...

python与php实现分割文件代码

python与php实现分割文件代码

前两天有个朋友说,想实现一个文本文件按照固定行数进行分割成多个文本文件,却不知如何实现。如果数据量小手动分割下就好了,如果数据量很大的话手动完成实在太耗费人力了,也不现实。那么就需要借助...

使用python和Django完成博客数据库的迁移方法

使用python和Django完成博客数据库的迁移方法

上一讲完成了基本博客的配置和项目工程的生成。这次开始将博客一些基本的操作主要是数据库方面学习。 1.设计博客数据库表结构 博客最主要的功能就是展示我们写的文章,它需要从某个地方获取博客文...

python自动生成model文件过程详解

生成方式 Python中想要自动生成 model文件可以通过 sqlacodegen这个命令来生成对应的model文件 sqlacodegen 你可以通过pip去安装: pip i...