-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.py
More file actions
64 lines (50 loc) · 2.02 KB
/
script.py
File metadata and controls
64 lines (50 loc) · 2.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
import argparse
import os
from datetime import datetime
fnt = ImageFont.truetype("arial.ttf", 30)
def arg_parser():
parser = argparse.ArgumentParser(
prog="Image Caption Slapper",
description="Image Caption Slapper is a python script used to put caption on a image with viral funny video style",
)
parser.add_argument("--path", "-p", help="image path", required=True)
parser.add_argument("--text", "-t", help="text to put in the image", required=True)
parser.add_argument("--out", "-o", help="output file name")
return parser.parse_args()
def editImage (imagePath, text, outputName):
editImage = Image.open(imagePath)
editImage = editImage.convert('RGBA')
drawer = ImageDraw.Draw(editImage)
imagesize = editImage.size
textSize = drawer.textbbox((0,0), text, font=fnt)
targetSize = [(imagesize[0] - textSize[2]) * 0.5, imagesize[1] * 0.75]
rectSize = [(0, imagesize[1] * 0.75), (imagesize[0], imagesize[1] * 0.84)]
overlay = Image.new('RGBA', imagesize, (0,0,0) + (0,))
drawOverlay = ImageDraw.Draw(overlay)
drawOverlay.rectangle(xy=rectSize, fill=(0,0,0, 128))
img = Image.alpha_composite(editImage, overlay)
img = img.convert('RGB')
imgDrawer = ImageDraw.Draw(img)
imgDrawer.text(targetSize, text, font=fnt, fill=(255, 255, 255, 255), align="center")
if not outputName:
filename, ext = outputFileName(imagePath)
output = filename + getcurrentdate() + "." + ext
img.save(output)
else:
img.save(outputName)
def outputFileName(path):
head, tail = os.path.split(path)
name = tail.split(".")[0]
ext = tail.split(".")[1]
return name, ext
def getcurrentdate():
now = datetime.now()
date = str(now.year) + str(now.month) + str(now.day) + "-" + str(now.hour) + str(now.minute) + str(now.second) + str(now.microsecond)
return date
def main():
args = arg_parser()
editImage(args.path, args.text, args.out)
main()