Python批量生成特定尺寸圖片及圖畫任意文字的實(shí)例
因?yàn)楣ぷ餍枰筛鞣N大小的圖片,所以寫了個小腳本,順便支持了下圖畫文字內(nèi)容。
具體代碼如下:
from PIL import Image, ImageDraw, ImageFont ''' Auth: Xiaowu Chen Note: Please install [pillow] library before run this script. ''' def draw_image(new_img, text, show_image=False): text = str(text) draw = ImageDraw.Draw(new_img) img_size = new_img.size draw.line((0, 0) + img_size, fill=128) draw.line((0, img_size[1], img_size[0], 0), fill=128) font_size = 40 fnt = ImageFont.truetype('arial.ttf', font_size) fnt_size = fnt.getsize(text) while fnt_size[0] > img_size[0] or fnt_size[0] > img_size[0]: font_size -= 5 fnt = ImageFont.truetype('arial.ttf', font_size) fnt_size = fnt.getsize(text) x = (img_size[0] - fnt_size[0]) / 2 y = (img_size[1] - fnt_size[1]) / 2 draw.text((x, y), text, font=fnt, fill=(255, 0, 0)) if show_image: new_img.show() del draw def new_image(width, height, text='default', color=(100, 100, 100, 255), show_image=False): new_img = Image.new('RGBA', (int(width), int(height)), color) draw_image(new_img, text, show_image) new_img.save(r'%s_%s_%s.png' % (width, height, text)) del new_img def new_image_with_file(fn): with open(fn, encoding='utf-8') as f: for l in f: l = l.strip() if l: ls = l.split(',') if '#' == l[0] or len(ls) < 2: continue new_image(*ls) if '__main__' == __name__: new_image(400, 300, 'hello world any size', show_image=True) # new_image_with_file('image_data.txt')
如果你需要批量的話,批量數(shù)據(jù)文件的格式如下:
#width,height,text 200,200,hello 300,255,world
執(zhí)行后的效果如下:
以上這篇Python批量生成特定尺寸圖片及圖畫任意文字的實(shí)例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python中if elif else及縮進(jìn)的使用簡述
這篇文章主要介紹了Python中if elif else及縮進(jìn)的使用,代碼簡單易懂,非常不錯,具有一定的參考借鑒價值,需要的朋友參考下吧2018-05-05Python實(shí)現(xiàn)批量導(dǎo)入1000條xlsx數(shù)據(jù)
本文主要介紹了Python實(shí)現(xiàn)批量導(dǎo)入1000條xlsx數(shù)據(jù),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-02-02Python學(xué)習(xí)筆記_數(shù)據(jù)排序方法
Python對數(shù)據(jù)排序有兩種方法:下面我們來簡單分析下2014-05-05python基礎(chǔ)之函數(shù)的定義和調(diào)用
這篇文章主要介紹了python函數(shù)的定義和調(diào)用,實(shí)例分析了Python中返回一個返回值與多個返回值的方法,需要的朋友可以參考下2021-10-10python 中os模塊os.path.exists()的用法說明
這篇文章主要介紹了python 中os模塊os.path.exists()的用法說明,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-03-03