Abdullah Diab’s Blog

Get Pattern From an Image in PIL Python

Two days ago I needed to generate a PIL image that is made up from repeating a pattern – another PIL image – multiple times, I didn’t find a code online to do it so I just wrote this small code to do it, thought might share it to help somebody out there.

def get_pattern_from_image(file_name, pattern_width, pattern_height):
    import Image
    pattern_image = Image.open(file_name, 'r')
    result_image = Image.new('RGB', (pattern_width, pattern_height))
    x = 0
    while x < pattern_width:
        y = 0
        while y < pattern_height:
            result_image.paste(pattern_image, (x, y))
            y += pattern_image.size[1]
        x += pattern_image.size[0]
    return result_image

It’s a very simple solution which uses the Image.paste method to repeat the pattern.

You can download this snippet of code from here: https://gist.github.com/4529367.

Enjoy 🙂