Python批量生成特定尺寸圖片及圖畫任意文字的實例
更新時間:2019年01月30日 09:50:27 作者:像風一樣的自由
今天小編就為大家分享一篇Python批量生成特定尺寸圖片及圖畫任意文字的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
因為工作需要生成各種大小的圖片,所以寫了個小腳本,順便支持了下圖畫文字內容。
具體代碼如下:
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批量生成特定尺寸圖片及圖畫任意文字的實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Python使用json模塊讀取和寫入JSON數(shù)據(jù)
Python 提供了內置的 json 模塊,使得我們可以方便地解析 JSON 數(shù)據(jù)(讀?。┖蜕?nbsp;JSON 數(shù)據(jù)(寫入),下面小編就來為大家介紹一下具體的操作步驟吧2025-03-03
python內置函數(shù)frozenset()的使用小結
本篇文章主要介紹了python內置函數(shù)frozenset()的使用小結,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-05-05
python網(wǎng)絡編程學習筆記(五):socket的一些補充
前面已經(jīng)為大家介紹了python socket的一些相關知識,這里為大家補充下,方便需要的朋友2014-06-06

