python實現(xiàn)圖片插入文字
更新時間:2019年11月26日 09:59:58 作者:staHuri
這篇文章主要為大家詳細(xì)介紹了python實現(xiàn)圖片插入文字,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了python圖片插入文字的具體代碼,供大家參考,具體內(nèi)容如下
問題
如何在圖片中插入大量文字并且自動換行
效果
原始圖
效果圖
注明
若需要寫入中文請使用中文字體
實現(xiàn)方式
from PIL import Image, ImageDraw, ImageFont class ImgText: font = ImageFont.truetype("micross.ttf", 24) def __init__(self, text): # 預(yù)設(shè)寬度 可以修改成你需要的圖片寬度 self.width = 100 # 文本 self.text = text # 段落 , 行數(shù), 行高 self.duanluo, self.note_height, self.line_height = self.split_text() def get_duanluo(self, text): txt = Image.new('RGBA', (100, 100), (255, 255, 255, 0)) draw = ImageDraw.Draw(txt) # 所有文字的段落 duanluo = "" # 寬度總和 sum_width = 0 # 幾行 line_count = 1 # 行高 line_height = 0 for char in text: width, height = draw.textsize(char, ImgText.font) sum_width += width if sum_width > self.width: # 超過預(yù)設(shè)寬度就修改段落 以及當(dāng)前行數(shù) line_count += 1 sum_width = 0 duanluo += '\n' duanluo += char line_height = max(height, line_height) if not duanluo.endswith('\n'): duanluo += '\n' return duanluo, line_height, line_count def split_text(self): # 按規(guī)定寬度分組 max_line_height, total_lines = 0, 0 allText = [] for text in self.text.split('\n'): duanluo, line_height, line_count = self.get_duanluo(text) max_line_height = max(line_height, max_line_height) total_lines += line_count allText.append((duanluo, line_count)) line_height = max_line_height total_height = total_lines * line_height return allText, total_height, line_height def draw_text(self): """ 繪圖以及文字 :return: """ note_img = Image.open("001.png").convert("RGBA") draw = ImageDraw.Draw(note_img) # 左上角開始 x, y = 0, 0 for duanluo, line_count in self.duanluo: draw.text((x, y), duanluo, fill=(255, 0, 0), font=ImgText.font) y += self.line_height * line_count note_img.save("result.png") if __name__ == '__main__': n = ImgText( "1234567890" * 5) n.draw_text()
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Python?lambda函數(shù)使用方法深度總結(jié)
在本文中,小編將帶大家學(xué)習(xí)一下Python中的lambda函數(shù),并探討使用它的優(yōu)點和局限性。文中的示例代碼講解詳細(xì),感興趣的可以了解一下2022-05-05python中如何實現(xiàn)鏈?zhǔn)秸{(diào)用
這篇文章主要介紹了python中如何實現(xiàn)鏈?zhǔn)秸{(diào)用,幫助大家更好的理解和學(xué)習(xí)使用python,感興趣的朋友可以了解下2021-03-03Python繪圖Matplotlib之坐標(biāo)軸及刻度總結(jié)
這篇文章主要介紹了Python繪圖Matplotlib之坐標(biāo)軸及刻度總結(jié),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-06-06