Created
June 2, 2017 12:06
-
-
Save shotasenga/7b27f9578aca9ccd694aa9fbfb6e8528 to your computer and use it in GitHub Desktop.
combine images from URL
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
import os, sys, random, string, tempfile | |
from urllib.request import urlopen | |
from urllib.parse import urlparse | |
from shutil import copyfileobj | |
from PIL import Image | |
src = sys.argv[1:] | |
def url_basename (url): | |
""" | |
return basename of the `url` | |
""" | |
return os.path.basename(urlparse(url).path) | |
def random_string (length): | |
""" | |
return random string | |
see https://stackoverflow.com/a/2257449/755333 | |
""" | |
return ''.join(random.choices(string.ascii_uppercase + string.ascii_lowercase + string.digits, k=length)) | |
# download all of images as temporary file | |
images = [] | |
for url in src: | |
filename = url_basename(url) | |
with urlopen(url) as response, tempfile.NamedTemporaryFile() as out_file: | |
copyfileobj(response, out_file) | |
images.append(Image.open(out_file.name)) | |
# combine images vertically | |
widths, heights = zip(*(im.size for im in images)) | |
combined = Image.new('RGB', (max(widths), sum(heights))) | |
offset = 0 | |
for im in images: | |
combined.paste(im, (0, offset)) | |
offset += im.size[1] | |
# save as a file | |
fname = random_string(10) + '.jpg' | |
combined.save(fname) | |
print(fname) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment