0
from PIL import Image
Image.MAX_IMAGE_PIXELS = None

# Opens an image
bg = Image.open('./images/1.jpg')

# The width and height of the background tile
bg_w, bg_h = bg.size

# Creates a new empty image, RGB mode, and size 1000 by 1000
new_im = Image.new('RGB', (7000,9240))

# The width and height of the new image
w, h = new_im.size

# Iterate through a grid, to place the background tile
for i in range(0, w, bg_w):
    for j in range(0, h, bg_h):
        # Change brightness of the images, just to emphasise they are unique copies
        # bg = Image.eval(bg, lambda x: x+(i+j)/1000)

        #paste the image at location i, j:
        new_im.paste(bg, (i, j))

new_im.save('./tiled/tiled-image1.png')

Been using the code above from: PIL fill background image repeatedly

Now Im trying to make it per folder instead of doing the images one by one. But can't make my code (below) to work. Could anyone help?

from PIL import Image


path = "./images/"

# Opens an image
bg = Image.open(path)

# The width and height of the background tile
bg_w, bg_h = bg.size

# Creates a new empty image, RGB mode, and size 1000 by 1000
new_im = Image.new('RGB', (7000,9240))



# The width and height of the new image
w, h = new_im.size

# Iterate through a grid, to place the background tile
for i in range(0, w, bg_w):
    for j in range(0, h, bg_h):
        # Change brightness of the images, just to emphasise they are unique copies
        # bg = Image.eval(bg, lambda x: x+(i+j)/1000)

        #paste the image at location i, j:
        new_im.paste(bg, (i, j))

new_im.save("./tiled/" + new_im + ".png")
new_im.show()

For sure I am missing something to run the code and get images in the folder but can't figure it out.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241

1 Answers1

0

You can use os.walk to iterate over your folders and subfolders:

import os
from PIL import Image
Image.MAX_IMAGE_PIXELS = None

INPUT_DIR = r'c:\so\69804229\images'
OUTPUT_DIR = r'c:\so\69804229\results'
IMAGE_EXT = ('.jpg', '.jpeg', '.png', '.gif')


for subdir, dirs, files in os.walk(INPUT_DIR):
    for file in files:
        if file.endswith(IMAGE_EXT):
            image_path = os.path.join(subdir, file)
            bg = Image.open(image_path)
            bg_w, bg_h = bg.size
            new_im = Image.new('RGB', (7000, 9240))
            w, h = new_im.size
            for i in range(0, w, bg_w):
                for j in range(0, h, bg_h):
                    new_im.paste(bg, (i, j))
            new_im.save(os.path.join(OUTPUT_DIR, file))
Alderven
  • 7,569
  • 5
  • 26
  • 38