Skip to content

Instantly share code, notes, and snippets.

@widnyana
Created January 8, 2016 11:44
Show Gist options
  • Select an option

  • Save widnyana/d96c5819fdad700c4d68 to your computer and use it in GitHub Desktop.

Select an option

Save widnyana/d96c5819fdad700c4d68 to your computer and use it in GitHub Desktop.
merge multi image into one using pillow
# -*- coding: utf-8 -*-
from PIL import Image
source = [
'picture_to_merge.page_0.jpg',
'picture_to_merge.page_1.jpg',
'picture_to_merge.page_2.jpg',
'picture_to_merge.page_3.jpg',
'picture_to_merge.page_4.jpg',
]
pwd = "/path/to/images"
stack = []
height = 0
width = 0
for i in source:
path = "{}/{}".format(pwd, i)
i = Image.open(path)
w, h = i.size
stack.append({
'source': i,
'width': w,
'height': h
})
#: check for image width
width = w if w > width else width
#: since I will merge the image verically, sum the height
height += h
#: create new canvas
new_img = Image.new('RGB', (width, height))
hpos = 0 #: height coordinate
for i in stack:
#: place the image to new canvas
new_img.paste(
i.get("source"),
(0, hpos) #: coordinate w, h
)
#: increment the height coordinate
hpos = hpos + i.get('height')
#: path to new image location
save = "{}/new.jpg".format(pwd)
#: save new image
new_img.save(save)
print("Ok, I'm done")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment