python使用PIL給圖片添加文字生成海報


python生成圖片海報

1.設計圖片模板

 

 

2.安裝python庫

環境:python3

安裝Pillow庫

pip install Pillow

3.具體代碼實現

新建 index.py

# -*- coding:utf-8 -*-

from PIL import Image, ImageDraw, ImageFont
import time

# 安裝庫:pip install Pillow

header = '001'
title = '日思錄第001篇'
books = ['中國史綱五十講', '再見拖延症', '心流']
writes = ['日思錄第001篇', 'python給圖片加文字']
summary = '習慣在一個任務開始之前,先給自己設立一個看起來不太可能達到的完美標准,並因為這個標准而遲遲無法動手,那你可能也是一個完美主義者'
n = 18
summary_list = [summary[i:i + n] for i in range(0, len(summary), n)]

# 圖片名稱
img = './test.png'  # 圖片模板
new_img = 'text.png'  # 生成的圖片
compress_img = 'compress.png'  # 壓縮后的圖片

# 設置字體樣式
font_type = '/System/Library/Fonts/STHeiti Light.ttc'
font_medium_type = '/System/Library/Fonts/STHeiti Medium.ttc'
header_font = ImageFont.truetype(font_medium_type, 55)
title_font = ImageFont.truetype(font_medium_type, 45)
font = ImageFont.truetype(font_type, 24)
color = "#000000"

# 打開圖片
image = Image.open(img)
draw = ImageDraw.Draw(image)
width, height = image.size

# header頭
header_x = 130
header_y = 690
draw.text((header_x, height - header_y), u'%s' % header, color, header_font)

# 標題
title_x = header_x
title_y = header_y - 80
draw.text((title_x, height - title_y), u'%s' % title, color, title_font)

# 當前時間
cur_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
cur_time_x = 590
cur_time_y = title_y - 25
cur_time_font = ImageFont.truetype(font_type, 25)
draw.text((cur_time_x, height - cur_time_y), u'%s' % cur_time, color, cur_time_font)

# 閱讀
book_x = title_x + 5
book_start_y = title_y - 190
book_y = 0
book_line = 50
for num, book in enumerate(books):
    y = book_start_y - num * book_line
    book_num = num + 1
    draw.text((book_x, height - y), u'%s. %s' % (book_num, book), color, font)

# 寫作
write_x = book_x
write_y = title_y - 450
write_line = 40

for num, write in enumerate(writes):
    write_num = num + 1
    y = write_y - num * write_line
    draw.text((write_x, height - y), u'%s. %s' % (write_num, write), color, font)

# 哲思
summary_x = book_x + 460
summary_y = book_start_y
summary_line = 35
for num, summary in enumerate(summary_list):
    y = summary_y - num * summary_line
    draw.text((summary_x, height - y), u'%s' % summary, color, font)

# 生成圖片
image.save(new_img, 'png')

# 壓縮圖片
sImg = Image.open(new_img)
w, h = sImg.size
width = int(w / 2)
height = int(h / 2)
dImg = sImg.resize((width, height), Image.ANTIALIAS)
dImg.save(compress_img)

執行結果

☁  python  python index.py

 

 結果

轉自:https://www.jianshu.com/p/2698af6c5892 僅供學習使用


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM