首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >如何使用PIL/Pillow将图像合并到画布中?

如何使用PIL/Pillow将图像合并到画布中?
EN

Stack Overflow用户
提问于 2012-05-18 13:46:00
回答 2查看 49.7K关注 0票数 51

我不熟悉PIL,但我知道在ImageMagick中将一堆图像放入网格中是非常容易的。

例如,我如何将16个图像放入一个4×4的网格中,在这个网格中我可以指定行和列之间的间距?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-05-18 16:35:42

这在PIL中也很容易做到。创建一个空图像,然后使用paste将图像粘贴到您需要的任何位置。下面是一个简单的例子:

代码语言:javascript
代码运行次数:0
运行
复制
import Image

#opens an image:
im = Image.open("1_tree.jpg")
#creates a new empty image, RGB mode, and size 400 by 400.
new_im = Image.new('RGB', (400,400))

#Here I resize my opened image, so it is no bigger than 100,100
im.thumbnail((100,100))
#Iterate through a 4 by 4 grid with 100 spacing, to place my image
for i in xrange(0,500,100):
    for j in xrange(0,500,100):
        #I change brightness of the images, just to emphasise they are unique copies.
        im=Image.eval(im,lambda x: x+(i+j)/30)
        #paste the image at location i,j:
        new_im.paste(im, (i,j))

new_im.show()

票数 94
EN

Stack Overflow用户

发布于 2019-01-07 07:40:31

在fraxel的伟大答案的基础上,我写了一个程序,它接收(.png)图像的文件夹,拼贴的宽度的像素数量,以及每行图片的数量,并为您完成所有的计算。

代码语言:javascript
代码运行次数:0
运行
复制
#Evan Russenberger-Rosica
#Create a Grid/Matrix of Images
import PIL, os, glob
from PIL import Image
from math import ceil, floor

PATH = r"C:\Users\path\to\images"

frame_width = 1920
images_per_row = 5
padding = 2

os.chdir(PATH)

images = glob.glob("*.png")
images = images[:30]                #get the first 30 images

img_width, img_height = Image.open(images[0]).size
sf = (frame_width-(images_per_row-1)*padding)/(images_per_row*img_width)       #scaling factor
scaled_img_width = ceil(img_width*sf)                   #s
scaled_img_height = ceil(img_height*sf)

number_of_rows = ceil(len(images)/images_per_row)
frame_height = ceil(sf*img_height*number_of_rows) 

new_im = Image.new('RGB', (frame_width, frame_height))

i,j=0,0
for num, im in enumerate(images):
    if num%images_per_row==0:
        i=0
    im = Image.open(im)
    #Here I resize my opened image, so it is no bigger than 100,100
    im.thumbnail((scaled_img_width,scaled_img_height))
    #Iterate through a 4 by 4 grid with 100 spacing, to place my image
    y_cord = (j//images_per_row)*scaled_img_height
    new_im.paste(im, (i,y_cord))
    print(i, y_cord)
    i=(i+scaled_img_width)+padding
    j+=1

new_im.show()
new_im.save("out.jpg", "JPEG", quality=80, optimize=True, progressive=True)

票数 16
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10647311

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档