溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Python批量生成特定尺寸圖片及圖畫任意文字的實(shí)例

發(fā)布時(shí)間:2020-10-08 17:48:49 來(lái)源:腳本之家 閱讀:107 作者:像風(fēng)一樣的自由 欄目:開發(fā)技術(shù)

因?yàn)楣ぷ餍枰筛鞣N大小的圖片,所以寫了個(gè)小腳本,順便支持了下圖畫文字內(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í)例

以上這篇Python批量生成特定尺寸圖片及圖畫任意文字的實(shí)例就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI