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)

效果图

python如何实现内容写在图片上

相关推荐