Created
January 8, 2016 11:44
-
-
Save widnyana/d96c5819fdad700c4d68 to your computer and use it in GitHub Desktop.
merge multi image into one using pillow
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # -*- 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