说明
视频剪辑时需要为视频添加字幕,添加字幕方法之一:根据字幕文本文件批量生成透明底只有字幕内容的图片文件,如下图,然后将这些图片文件添加到视频剪辑软件轨道中。
于是用pillow这Python图片工具库执行本次批量生成工作。
前提
1
|
pip intall pillow |
放码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
|
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字幕图片内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://blog.csdn.net/u011863024/article/details/124893579