如果问一个前端,如何将多个图片或者文字组合成一段视频,脑海中你会想到哪些黑科技。我们的目标最终的产物,比如是一段视频,方便在不同的场景下进行传播。
之前实践过一个项目,就做到了在移动端通过持续对canvas进行截图,并对截图进行拼接搭配音效完成一段比较优雅的视频。整个闭环都在移动端完成,整体性能还是比较不错的。这个技术细节,有时间再单开一文吧。
直接分享一段干货,需要的自取,先看效果视频:
此处为语雀视频卡片,点击链接查看:output_video.mp4
import os
from moviepy.editor import ImageClip, concatenate_videoclips
from moviepy.editor import *
from skimage.filters import gaussian
import cv2
# 图片文件夹路径和图片格式
image_folder = 'images/'
image_format = '.jpg'
BASE_RATIO = (1280 * 4, 720 * 4)
# 定义高斯模糊函数
def apply_blur(image, ksize=101):
return cv2.GaussianBlur(image, (ksize, ksize), 0)
def formateImage(image):
b,g,r = cv2.split(image)
image = cv2.merge([r,g,b])
return image
# 获取文件夹中的所有图片
image_files = [f for f in os.listdir(image_folder) if f.endswith(image_format)]
# 根据文件名对图片进行排序
image_files.sort()
# 定义图片变大动画的缩放参数和持续时间
scale_factor = 2
duration = 4
# 创建一个空的视频剪辑列表
clips = []
contentsClips = []
# 为每张图片创建一个带有逐渐变大动画的视频剪辑,并添加到列表中
BASE_START = 0
def changePosition(t):
# return (0, 0)
return ('center', 'center')
def changeSize(t):
return (t / duration * 0.2) + 0.4
# return 0.4
for index, image_file in enumerate(image_files):
image_path = os.path.join(image_folder, image_file)
image = cv2.imread(image_path)
shape = image.shape
w = shape[1]
h = shape[2]
image = formateImage(image)
blurred_image = apply_blur(image)
blur_clip = ImageClip(blurred_image, duration=duration)
blur_clip = blur_clip.resize(BASE_RATIO)
blur_clip = blur_clip.set_start(BASE_START + index * duration)
clips.append(blur_clip)
imageMain = cv2.imread(image_path)
imageMain = formateImage(imageMain)
shape = imageMain.shape
w = shape[1]
h = shape[0]
image_clip = ImageClip(imageMain, duration= duration)
image_clip = image_clip.resize((w / h * (BASE_RATIO[1] * 2), (BASE_RATIO[1] * 2)))
image_clip = image_clip.set_start(BASE_START + index * duration)
image_clip = image_clip.resize(changeSize)
image_clip = image_clip.set_position(changePosition)
clips.append(image_clip)
# 拼接所有视频
final_video = CompositeVideoClip(clips, size=BASE_RATIO)
# 保存视频
final_video.write_videofile('output_video.mp4', fps=60, codec='libx264')