您好,登錄后才能下訂單哦!
這篇文章主要介紹python實(shí)現(xiàn)內(nèi)容寫在圖片上的方法,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!
具體代碼內(nèi)容如下:
# -*- 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 = "的氣質(zhì)適合開" 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數(shù)據(jù)初始化 self.pic_handle() self.base_64() def base_64(self): """ 將圖片讀成base64的格式,返回給移動(dòng)端渲染 :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" # 底圖的操作對(duì)象 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 # 寫在底圖上的區(qū)域,計(jì)算字符串的長度,讓它寬度居中(高度居中 同理) # name_loaction分別指寬高,圖片左上角為(0,0)坐標(biāo) # 寫字,fill為字體顏色,RGB值 # try except 避免字符串編碼的問題(unicode編碼 再次轉(zhuǎn)換會(huì)報(bào)錯(cuò)) 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實(shí)現(xiàn)內(nèi)容寫在圖片上的方法的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對(duì)大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。