我有一堆图像(比如10)我已经生成了数组或PIL对象。
我需要将它们整合成循环方式来显示它们,它应该根据屏幕的分辨率调整自己,python中有什么可以做到这一点吗?
我尝试过使用粘贴,但是弄清楚分辨率画布和粘贴位置是很痛苦的,想知道是否有更简单的解决方案?
答案 0 :(得分:5)
我们可以说当相邻点之间存在恒定角度theta
时,点均匀排列成圆形。 theta
可以计算为2 * pi弧度除以点数。第一个点是相对于x轴的角度0
,角度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")
结果: