看程序员如何使用Python快速给视频添加字幕

# coding=utf-8

import matplotlib.pyplot as plt
from PIL import Image,ImageDraw,ImageFont

bg_size = (1920,1080)
bg_color = (0,0,0)
font_file = "C:/Users/wangle/AppData/Local/Microsoft/Windows/Fonts/汉仪雅酷黑W.ttf" #方正粗圆_GBK
font_size = 65
contex_color = (255,255,255)
height_ratio = 0.9

def gen(index,contex):
    if index / 1000 >= 1:
        index = str(index)
    elif index / 100 >= 1:
        index = '0' + str(index)
    elif index / 10 >= 1:
        index = '00' + str(index)
    else:
        index = '000' + str(index)
    
    img = Image.new(mode = "RGB", size = bg_size, color = bg_color)
    draw = ImageDraw.Draw(img, mode = "RGB")
    font = ImageFont.truetype(font_file, size = font_size)
    text_width = font.getsize(contex)
    text_coordinate = int((bg_size[0]-text_width[0]) * 0.5), int((bg_size[1]-text_width[1])* height_ratio)
    draw.text(text_coordinate, contex, contex_color, font=font)

    img = img.convert('RGBA')
    L,H = img.size
    color_0 = img.getpixel((0,0))
    for h in range(H):
        for l in range(L):
            dot = (l,h)
            color_1 = img.getpixel(dot)
            if color_1 == color_0:
                color_1 = color_1[:-1] + (0,)
                img.putpixel(dot,color_1)

    img.save('E:/vlog/第八期/subtitle/%s_%s.png' % (index,contex),'png')
    img.show()

with open('E:/vlog/第八期/20200319_165611.txt','r',encoding='utf8') as f:
    for i,text in enumerate( f.readlines()):
        text = text.strip()
        if text:
            gen(i,text)
        if i > 7:
            break

根据txt文件:
在这里插入图片描述
生成背景颜色透明的图片 图片下方含文字:
在这里插入图片描述
在这里插入图片描述

将这些图片放入剪辑软件中即可覆盖在视频素材上面:
在这里插入图片描述

  • 2
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

虚坏叔叔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值