Python批量生成特定尺寸圖片及圖畫(huà)任意文字的實(shí)例
因?yàn)楣ぷ餍枰筛鞣N大小的圖片,所以寫(xiě)了個(gè)小腳本,順便支持了下圖畫(huà)文字內(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批量生成特定尺寸圖片及圖畫(huà)任意文字的實(shí)例就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python中if elif else及縮進(jìn)的使用簡(jiǎn)述
這篇文章主要介紹了Python中if elif else及縮進(jìn)的使用,代碼簡(jiǎn)單易懂,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2018-05-05
Python實(shí)現(xiàn)批量導(dǎo)入1000條xlsx數(shù)據(jù)
本文主要介紹了Python實(shí)現(xiàn)批量導(dǎo)入1000條xlsx數(shù)據(jù),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-02-02
Python學(xué)習(xí)筆記_數(shù)據(jù)排序方法
Python對(duì)數(shù)據(jù)排序有兩種方法:下面我們來(lái)簡(jiǎn)單分析下2014-05-05
Python的類實(shí)例屬性訪問(wèn)規(guī)則探討
這篇文章主要介紹了Python的類實(shí)例屬性訪問(wèn)規(guī)則,本文總結(jié)了一些對(duì)C++和Java程序員來(lái)說(shuō)不是很直觀的地方來(lái)說(shuō)明Python中的類實(shí)例屬性訪問(wèn),需要的朋友可以參考下2015-01-01
python基礎(chǔ)之函數(shù)的定義和調(diào)用
這篇文章主要介紹了python函數(shù)的定義和調(diào)用,實(shí)例分析了Python中返回一個(gè)返回值與多個(gè)返回值的方法,需要的朋友可以參考下2021-10-10
python 中os模塊os.path.exists()的用法說(shuō)明
這篇文章主要介紹了python 中os模塊os.path.exists()的用法說(shuō)明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-03-03

