python如何实现内容写在图片上
本文实例为大家分享了python将内容写在图片上的具体代码,供大家参考,具体内容如下
# -*- coding: utf-8 -*- # Created on 2018/3/20 import base64 import random import os import sys import time from PIL import Image, ImageFont, ImageDraw reload(sys) sys.setdefaultencoding('utf8') BASE_PATH = "E:\\MyWork\\qingwa\\5\\" # 底图所在路径 TMP_PATH = "E:\\MyWork\\qingwa\\5\\tmp\\" # 生成图片缓存路径 font_size = 35 # 216 194 119 class MyCar: def __init__(self, name): self.name = name self.name_append = "的气质适合开" if not os.path.exists(TMP_PATH): os.mkdir(TMP_PATH) self.end_path = TMP_PATH + str(int(time.time())) + str(random.randint(100, 999)) + ".png" # 图片处理完之后保存的文件名 self.data = "" # base64数据初始化 self.pic_handle() self.base_64() def base_64(self): """ 将图片读成base64的格式,返回给移动端渲染 :return: """ res = open(self.end_path, 'rb') base64_data = base64.b64encode(res.read()) res.close() d = { 'image': 'data:image/jpg;base64,' + base64_data } self.data = d def pic_handle(self): # 底图路径 img_path = BASE_PATH + str(random.randint(1, 8)) + ".jpg" # 底图的操作对象 font_img = Image.open(img_path).convert("RGBA") # 即将在该底图上写字 draw = ImageDraw.Draw(font_img) # 画笔 name_font = ImageFont.truetype("wryh.TTF", size=35) # 即将写的字 name = self.name + self.name_append # 底图的宽高 w, h = font_img.size # 写在底图上的区域,计算字符串的长度,让它宽度居中(高度居中 同理) # name_loaction分别指宽高,图片左上角为(0,0)坐标 # 写字,fill为字体颜色,RGB值 # try except 避免字符串编码的问题(unicode编码 再次转换会报错) try: name_location = (((w - len(unicode(name, "UTF-8")) * font_size) / 2), 76) draw.text(name_location, unicode(name, "UTF-8"), fill=(216, 194, 119), font=name_font) except BaseException as e: print e.message name_location = (((w - len(name) * font_size) / 2), 76) draw.text(name_location, name, fill=(216, 194, 119), font=name_font) print self.end_path # 保存处理好的图片 font_img.save(self.end_path) # 显示图片 font_img.show() def end_data(self): return self.data if __name__ == '__main__': my_car = MyCar("测试") return_data = my_car.end_data() print type(return_data)
效果图
相关推荐
pythonjw 2020-11-17
hedongli 2020-09-01
浪味仙 2020-08-17
IT兄弟团 2020-08-01
凉白开 2020-07-19
kjh00abc 2020-07-08
Skyline 2020-06-28
苦咖啡flask 2020-06-18
万物weiyi 2020-06-16
半纸药笺 2020-06-14
chenhaimeimeng 2020-06-13
JF0 2020-06-13
逍遥友 2020-06-02
kyelu 2020-06-02
northwindx 2020-05-31
tengyuan 2020-05-30
singer 2020-05-30
GreatZhou 2020-05-28
coolhty 2020-05-20