用Python批量生成字幕图片用于视频剪辑

说明

视频剪辑时需要为视频添加字幕,添加字幕方法之一:根据字幕文本文件批量生成透明底只有字幕内容的图片文件,如下图,然后将这些图片文件添加到视频剪辑软件轨道中。
用Python批量生成字幕图片用于视频剪辑_第1张图片
于是用pillow这Python图片工具库执行本次批量生成工作。

前提

  1. 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)

参考

  1. 《Python编程快速上手—让繁琐工作自动化》
  2. 【PR教程】PR如何快速批量制作字幕?还能实时修改!
  3. Pillow doc

你可能感兴趣的:(Python,python,视频字幕,pillow)