Last active
June 18, 2018 15:44
-
-
Save ivandjuricic/427427c01fed384ba10def5c2ebd18a6 to your computer and use it in GitHub Desktop.
MEMEIC MEME generator
This file contains 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 sys | |
import requests | |
import io | |
import tempfile | |
import os | |
from string import Template | |
from PIL import Image | |
from PIL import ImageFont | |
from PIL import ImageDraw | |
template_url = "https://i.imgur.com/ctd64Wp.jpg" | |
start_x = 52 | |
end_x = 700 | |
start_y = 158 | |
TEMPLATE_STRING = Template("Moj $name, propade zivot ispred $what, a to nema cijenu.") | |
def find_occurences(s, ch): | |
return [i for i, letter in enumerate(s) if letter == ch] | |
if __name__ == "__main__": | |
name = sys.argv[1] | |
what = sys.argv[2] | |
output_string = TEMPLATE_STRING.substitute(name=name, what=what) | |
r = requests.get(template_url, stream=True) | |
buffer = tempfile.SpooledTemporaryFile(max_size=1e9) | |
if r.status_code == 200: | |
downloaded = 0 | |
filesize = int(r.headers['content-length']) | |
for chunk in r.iter_content(): | |
downloaded += len(chunk) | |
buffer.write(chunk) | |
buffer.seek(0) | |
img = Image.open(io.BytesIO(buffer.read())) | |
rgb_im = img.convert('RGB') | |
draw = ImageDraw.Draw(rgb_im) | |
font = ImageFont.truetype("Helvetica.ttc", 30) | |
whitespace_positions = find_occurences(output_string, " ") | |
for position in whitespace_positions: | |
splitted_string = output_string[0:position] | |
if font.getsize(splitted_string)[0] + 52 > end_x - start_x: | |
first_line = output_string[:position] | |
second_line = output_string[position+1:] | |
break | |
draw.text([start_x, start_y], first_line, font=font, fill=(32,32,32,255)) | |
draw.text([start_x, start_y + 36], second_line, font=font, fill=(32,32,32,255)) | |
rgb_im.save(os.path.join('down_image.jpg'), quality=85) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment