I am new to pil package. I wish to merge only those images whose name is in the list.
w.txt file contains these filename
1
2
Folder contains 4 images 1.png, 2.png, 3.png and 4.png
from PIL import Image
with open('w.txt') as f:
my_list =list(f)
print(my_list)
img_01 = Image.open("1.png")
img_02 = Image.open("2.png")
img_03 = Image.open("3.png")
img_04 = Image.open("4.png")
img_01_size = img_01.size
img_02_size = img_02.size
img_03_size = img_02.size
img_02_size = img_02.size
new_im = Image.new('RGB', (2*img_01_size[0],2*img_01_size[1]), (250,250,250))
new_im.paste(img_01, (0,0))
new_im.paste(img_02, (img_01_size[0],0))
new_im.paste(img_03, (0,img_01_size[1]))
new_im.paste(img_04, (img_01_size[0],img_01_size[1]))
new_im.save("merged_images.png", "PNG")
Unsure of where to loop within pil. kindly help.
This code should work (I haven tested it on a small sample of 5 images in a 3x2 grid). Of course, if the grid's size depends on the number of images, you'll want to replace the values for grid_width
and grid_height
in the code with values calculated from len(my_images):
from PIL import Image
with open('w.txt') as f:
my_list =list(f)
print(my_list)
my_images = [Image.open(f"{i.strip()}.png") for i in my_list if i.strip()]
width, height = my_images[0].size
grid_width, grid_height = 6, 6
new_im = Image.new('RGB', (grid_width * width, grid_height * height), (250,250,250))
for i, image in enumerate(my_images):
y, x = divmod(i, grid_width)
new_im.paste(image, (x * width, y * height))
new_im.save("merged_images.png", "PNG")