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程序设计有所帮助。

相关文章

Django接受前端数据的几种方法总结

背景 测试工具箱写到一半,今天遇到了一个前后端数据交互的问题,就一起做一下整理。 环境 -------------------------------------------------...

python获取全国城市pm2.5、臭氧等空气质量过程解析

随着国家发展,中国很多城市的空气质量其实并不好,国家气象局会有实时统计,但是要去写爬虫爬取是十分麻烦的事情,并且官方网站也会做一些反爬虫措施,所以实现起来比较麻烦,最好的办法就是使用现成...

Python中的choice()方法使用详解

choice()方法从一个列表,元组或字符串返回一个随机项。 语法 以下是choice()方法的语法: choice( seq ) 注意:此函数是无法直接访问的,所以我们需要导...

Python学习小技巧之列表项的推导式与过滤操作

本文介绍的是关于Python中列表项的推导式与过滤操作的相关内容,分享出来供大家参考学习,下面来一起看看吧: 典型代码1: data_list = [1, 2, 3, 4, 0, -...

python中利用numpy.array()实现俩个数值列表的对应相加方法

小编想把用python将列表[1,1,1,1,1,1,1,1,1,1] 和 列表 [2,2,2,2,2,2,2,2,2,2]对应相加成[3,3,3,3,3,3,3,3,3,3]。 代码如...