这是一些工作代码。
你打电话时Image.open(p)
,它返回一个 Image 对象,因此您需要将其存储在变量中:im = Image.open(p)
.
我不知道什么image=Image.eval(p, lambda x: x+(col+row)/30)
是为了这样做我把它删除了。
size
是缩略图的大小,但您没有使用该变量。打开图像后,应将其调整为size
.
我将 Picturewidth 和 Pictureheight 重命名为thumbnail_width 和thumbnail_height,以明确它们是什么并遵循 Python 命名约定。
我还将列数和行数移至变量,以便可以在没有幻数的情况下重复使用它们。
第一个循环将每个图像打开为im
,对其进行缩略图并将其放入列表中ims
.
在下一个循环之前我们初始化i,
x, and
y` 变量来跟踪我们正在查看的图像,以及 x 和 y 坐标以将缩略图粘贴到更大的画布中。它们将在下一个循环中更新。
第一个循环针对列 (cols
),而不是像素(width
)。 (还range(0, thing)
做同样的事range(thing)
.)
类似地,第二个循环是针对行而不是像素。在这个循环中,我们将当前图像粘贴到ims[i]
进入大new_im
at x, y
。这些是像素位置,而不是行/列位置。
在内循环结束时,增加i
计数器,并添加thumbnail_height
to y
.
同样,在外循环的末尾,添加thumnnail_width
to x
并重置y
为零。
你只需要保存new_im
一次,在这些循环完成之后。
不需要串联"Image2" + ".jpg"
等等,只需做“Image2.jpg”。
这会导致这样的结果:
这段代码可以改进。例如,如果您不需要它们做其他任何事情,则无需保存中间 ImageX.jpg 文件,而不是将这些文件名放入listofimages
,将图像直接放在那里:listofimages = [im, out1, out2, etc...]
,然后替换for p in listofimages:
with for im in listofimages:
并删除im = Image.open(p)
.
您还可以计算图像的一些填充,使黑色空间均匀。
from PIL import Image
im= Image.open('Tulips.jpg')
out=im.convert("RGB", (
0.412453, 0.357580, 0.180423, 0,
0.212671, 0.715160, 0.072169, 0,
0.019334, 0.119193, 0.950227, 0 ))
out.save("Image2.jpg")
out2=im.convert("RGB", (
0.9756324, 0.154789, 0.180423, 0,
0.212671, 0.715160, 0.254783, 0,
0.123456, 0.119193, 0.950227, 0 ))
out2.save("Image3.jpg")
out3= im.convert("1")
out3.save("Image4.jpg")
out4=im.convert("RGB", (
0.986542, 0.154789, 0.756231, 0,
0.212671, 0.715160, 0.254783, 0,
0.123456, 0.119193, 0.112348, 0 ))
out4.save("Image5.jpg")
out5=Image.blend(im, out4, 0.5)
out5.save("Image6.jpg")
listofimages=['Tulips.jpg', 'Image2.jpg', 'Image3.jpg', 'Image4.jpg', 'Image5.jpg', 'Image6.jpg']
def create_collage(width, height, listofimages):
cols = 3
rows = 2
thumbnail_width = width//cols
thumbnail_height = height//rows
size = thumbnail_width, thumbnail_height
new_im = Image.new('RGB', (width, height))
ims = []
for p in listofimages:
im = Image.open(p)
im.thumbnail(size)
ims.append(im)
i = 0
x = 0
y = 0
for col in range(cols):
for row in range(rows):
print(i, x, y)
new_im.paste(ims[i], (x, y))
i += 1
y += thumbnail_height
x += thumbnail_width
y = 0
new_im.save("Collage.jpg")
create_collage(450, 300, listofimages)