Python批量生成字幕圖片的方法詳解

說明

視頻剪輯時需要為視頻添加字幕,添加字幕方法之一:根據字幕文本文件批量生成透明底隻有字幕內容的圖片文件,如下圖,然後將這些圖片文件添加到視頻剪輯軟件軌道中。

於是用pillow這Python圖片工具庫執行本次批量生成工作。

前提

pip intall pillow

放碼

from PIL import Image, ImageDraw, ImageFont
import os

imageWidth, imageHeight = 1920, 1080
fontsFolderPath = 'C:\\Users\\Jallen\\AppData\\Local\\Microsoft\\Windows\\Fonts'
fontFilePath = os.path.join(fontsFolderPath, 'Alibaba-PuHuiTi-Regular.otf')

def test():
    im = Image.new('RGBA', (imageWidth, imageHeight))
    draw = ImageDraw.Draw(im)
    text='你好,字體'
    alibabaFont = ImageFont.truetype(fontFilePath, 50)
    textSize = alibabaFont.getsize(text)
    startX = (imageWidth - textSize[0]) / 2.0
    startY = (imageHeight - textSize[1]) / 2.0

    draw.text((startX, startY), text, fill='white', font=alibabaFont, stroke_width=1, stroke_fill='black')
    im.save('test.png')

def makeImageWithOneLine(imWidth, imHeight, textY, text, imFileName, fontSize=50):
    im = Image.new('RGBA', (imWidth, imHeight))
    draw = ImageDraw.Draw(im)
    alibabaFont = ImageFont.truetype(fontFilePath, fontSize)
    textSize = alibabaFont.getsize(text)
    startX = (imWidth - textSize[0]) / 2.0 #水平居中
    startY = textY#(imHeight - textSize[1]) / 2.0

    draw.text((startX, startY), text, fill='white', font=alibabaFont, stroke_width=1, stroke_fill='black')
    im.save(imFileName)


def makeImageWithTwoLines(imWidth, imHeight, textY, text1, text2, imFileName, fontSize1=50, fontSize2=50):
    im = Image.new('RGBA', (imWidth, imHeight))
    draw = ImageDraw.Draw(im)

    alibabaFont1 = ImageFont.truetype(fontFilePath, fontSize1)#如有必要,可緩存起來
    alibabaFont2 = ImageFont.truetype(fontFilePath, fontSize2)
    
    textSize1 = alibabaFont1.getsize(text1)
    textSize2 = alibabaFont2.getsize(text2)
    
    startX1 = (imWidth - textSize1[0]) / 2.0 #水平居中
    startY1 = textY#(imHeight - textSize1[1]) / 2.0
    
    startX2 = (imWidth - textSize2[0]) / 2.0
    startY2 = startY1 + textSize1[1]

    draw.text((startX1, startY1), text1, fill='white', font=alibabaFont1, stroke_width=1, stroke_fill='black')
    draw.text((startX2, startY2), text2, fill='white', font=alibabaFont2, stroke_width=1, stroke_fill='black')
    
    im.save(imFileName)

if  __name__ == '__main__':
    #test()
    inFile = open("in/a.txt", encoding="utf-8")#字幕文件
    count = 0
    for line in inFile.readlines():
        en, ch = line.split("/")
        print(line)
        #makeImageWithOneLine(imageWidth, imageHeight, 1000, en, "out/subtitle_%d.png" % count)
        makeImageWithTwoLines(imageWidth, imageHeight, imageHeight - 130, en, ch, \
            "out/subtitle_%d.png" % count, 60, 30)
        count += 1
        #print(ch)

到此這篇關於Python批量生成字幕圖片的方法詳解的文章就介紹到這瞭,更多相關Python字幕圖片內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: