|
@@ -0,0 +1,39 @@
|
|
|
+from PIL import Image,ImageDraw,ImageFont
|
|
|
+import re
|
|
|
+
|
|
|
+def trim_punctuation(s):
|
|
|
+ pat_block = u'[^\u4e00-\u9fff0-9a-zA-Z]+'
|
|
|
+ pattern = u'([0-9]+{0}[0-9]+)|{0}'.format(pat_block)
|
|
|
+ res = re.sub(pattern, lambda x: x.group(1) if x.group(1) else u" " ,s)
|
|
|
+
|
|
|
+def text2image(content, save_target, **args):
|
|
|
+ unicode_text = trim_punctuation(content)
|
|
|
+ font = ''
|
|
|
+ if args["lang"]=='zh':
|
|
|
+ font = ImageFont.truetype(font="/FONTS/NotoSansTC-Regular.otf", size=args["size"])
|
|
|
+ elif args["lang"]=='中文':
|
|
|
+ font = ImageFont.truetype(font="/FONTS/NotoSansTC-Regular.otf", size=args["size"])
|
|
|
+ elif args["lang"]=='日文':
|
|
|
+ font = ImageFont.truetype(font="/FONTS/NotoSansJP-Regular.otf", size=args["size"])
|
|
|
+ elif args["lang"]=='泰文':
|
|
|
+ font = ImageFont.truetype(font="/FONTS/NotoSansThai-Regular.ttf", size=args["size"])
|
|
|
+ elif args["lang"]=='馬來文':
|
|
|
+ font = ImageFont.truetype(font="/FONTS/NotoSansMalayalam-Regular.ttf", size=args["size"])
|
|
|
+ else :
|
|
|
+ font = ImageFont.truetype(font="/FONTS/NotoSans-Regular.ttf", size=args["size"])
|
|
|
+ W, H = (1280,720)
|
|
|
+ canvas = Image.new('RGBA', (W, H), "#00000000")
|
|
|
+ draw = ImageDraw.Draw(canvas)
|
|
|
+ text= content
|
|
|
+
|
|
|
+ w = draw.textlength(content,font = font)
|
|
|
+ #draw.text(((W-w)/2,0), text,'black', font)
|
|
|
+ #text_border(draw,(W-w)/2,0,text,font,(83, 49, 0),'black')
|
|
|
+ fill = tuple(args["fill"]) if type(args["fill"]) == list else args["fill"]
|
|
|
+ stroke_fill = tuple(args["stroke_fill"]) if type(args["stroke_fill"]) == list else args["stroke_fill"]
|
|
|
+ draw.multiline_text(((W-w)/2,0), text,font=font, fill=fill, stroke_fill=stroke_fill, stroke_width=args["stroke_width"], align="right")
|
|
|
+ canvas.save(str(save_target), "PNG")
|
|
|
+
|
|
|
+
|
|
|
+if __name__ == "__main__":
|
|
|
+ text2image("This is test text. 這是測試文本。", "./black_15.png", lang="zh", size=15, fill='black', stroke_fill='white', stroke_width=0, align="right")
|