Python批量生成特定尺寸圖片及圖畫任意文字的實例-創(chuàng)新互聯(lián)

因為工作需要生成各種大小的圖片,所以寫了個小腳本,順便支持了下圖畫文字內(nèi)容。

創(chuàng)新互聯(lián)建站專注于企業(yè)網(wǎng)絡(luò)營銷推廣、網(wǎng)站重做改版、佳縣網(wǎng)站定制設(shè)計、自適應(yīng)品牌網(wǎng)站建設(shè)、H5建站、成都做商城網(wǎng)站、集團公司官網(wǎng)建設(shè)、成都外貿(mào)網(wǎng)站建設(shè)公司、高端網(wǎng)站制作、響應(yīng)式網(wǎng)頁設(shè)計等建站業(yè)務(wù),價格優(yōu)惠性價比高,為佳縣等各大城市提供網(wǎng)站開發(fā)制作服務(wù)。

具體代碼如下:

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')
 
 

另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務(wù)器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國服務(wù)器、虛擬主機、免備案服務(wù)器”等云主機租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務(wù)可用性高、性價比高”等特點與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場景需求。

當前名稱:Python批量生成特定尺寸圖片及圖畫任意文字的實例-創(chuàng)新互聯(lián)
當前路徑:http://www.muchs.cn/article14/dodege.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供App開發(fā)、ChatGPT、云服務(wù)器品牌網(wǎng)站建設(shè)、網(wǎng)站設(shè)計公司營銷型網(wǎng)站建設(shè)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

成都網(wǎng)頁設(shè)計公司