Skip to content

Instantly share code, notes, and snippets.

@jay-pee
Forked from glombard/combine.py
Last active June 26, 2019 21:04
Show Gist options
  • Save jay-pee/11f13ed579b28c0e90be001172776c4e to your computer and use it in GitHub Desktop.
Save jay-pee/11f13ed579b28c0e90be001172776c4e to your computer and use it in GitHub Desktop.
Merging 4 images into one with Python and PIL/Pillow
#!/usr/bin/env python3
# encoding: utf8
'''
Combine multiple images into one.
Forked from Gert Lombard.
To install the Pillow and Docopt module on Mac OS X:
$ xcode-select --install
$ brew install libtiff libjpeg webp little-cms2
$ pip install Pillow
$ pip install docopt==0.6.2
Usage:
combine [-d <dir> | -o <file> | -c <columns>]
Options:
-d <dir> Some directory [default: ./]
-o <file> file [default: image_combined.jpg]
-c <columns> Columns [default: 2]
'''
from __future__ import print_function
import os
from docopt import docopt
from PIL import Image
if __name__ == '__main__':
arguments = docopt(__doc__, version='Combine 1.0')
files =[]
dir = arguments['-d']
outputFileName = arguments['-o']
columns = int(arguments['-c'])
print("Filelist:")
for f in os.listdir(dir):
if os.path.splitext(f)[1].lower() in ('.jpg', '.jpeg') and not f==outputFileName:
files.append(f)
print (f)
print("")
hights = 0
width = 0
currentWidths = 0
currentHights = 0
for i,f in enumerate(files):
path = os.path.expanduser(dir+f)
w, h = Image.open(path).size
currentWidths += w
if h > currentHights:
currentHights = h
if i % columns == columns-1: #If last column
if currentWidths > width:
width = currentWidths
currentWidths = 0
if i % columns == 0: #If start a new row
hights+=currentHights
currentHights = 0
result = Image.new('RGB', (width, hights))
x=0
y=0
for index, file in enumerate(files):
path = os.path.expanduser(dir+file)
img = Image.open(path)
w, h = img.size
print('pos {0},{1} size {2},{3}'.format(x, y, w, h))
result.paste(img, (x, y, x + w, y + h))
x += w
if index % columns == columns-1:
y += h
x = 0
result.save(os.path.expanduser(outputFileName))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment