1

我有一堆图像(比如 10 个)我已经生成为数组或 PIL 对象。

我需要将它们集成到圆形方式中以显示它们,它应该根据屏幕的分辨率自行调整,python 中有什么可以做到这一点吗?

我尝试过使用粘贴,但是弄清楚要粘贴的分辨率画布和位置很痛苦,想知道是否有更简单的解决方案?

4

1 回答 1

7

theta当相邻点之间的角度恒定时,我们可以说点均匀排列在一个圆圈中。theta可以计算为 2*pi 弧度除以点数。第一个点0与 x 轴成角度,第二个点成角度theta*1,第三个点成角度theta*2,等等。

使用简单的三角函数,您可以找到位于圆边缘上的任何点的 X 和 Y 坐标。ohm对于位于半径为 的圆上的角度点r

xFromCenter = r*cos(ohm)
yFromCenter = r*sin(ohm)

使用这个数学,可以将图像均匀地排列在一个圆圈上:

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, curImg in enumerate(imagesToArrange):
        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))

#red.png, blue.png, green.png are simple 50x50 pngs of solid color
imageFilenames = ["red.png", "blue.png", "green.png"] * 5
images = [Image.open(filename) for filename in imageFilenames]

arrangeImagesInCircle(img, images)

img.save("output.png")

结果:

在此处输入图像描述

于 2012-11-14T17:53:12.533 回答