重慶分公司,新征程啟航
為企業提供網站建設、域名注冊、服務器等服務
為企業提供網站建設、域名注冊、服務器等服務
這篇文章給大家介紹使用Python怎么在圖片中插入大量文字,內容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
實現方式
from PIL import Image, ImageDraw, ImageFont class ImgText: font = ImageFont.truetype("micross.ttf", 24) def __init__(self, text): # 預設寬度 可以修改成你需要的圖片寬度 self.width = 100 # 文本 self.text = text # 段落 , 行數, 行高 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: # 超過預設寬度就修改段落 以及當前行數 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): # 按規定寬度分組 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()
關于使用Python怎么在圖片中插入大量文字就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
另外有需要云服務器可以了解下創新互聯scvps.cn,海內外云服務器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務器、裸金屬服務器、高防服務器、香港服務器、美國服務器、虛擬主機、免備案服務器”等云主機租用服務以及企業上云的綜合解決方案,具有“安全穩定、簡單易用、服務可用性高、性價比高”等特點與優勢,專為企業上云打造定制,能夠滿足用戶豐富、多元化的應用場景需求。