Python 生成视频缩略图
代码如下:
# coding=utf-8
import os
import cv2
from PIL import Image
from flask import Flask, request
from flask_cors import *
import json
app = Flask(__name__)
@app.route('/', methods=['POST'])
def index():
# 接收文件
file = request.files['file']
videoName, videoPath = file.filename[0:-4], './video.mp4'
file.save(videoPath)
# 读取第一帧
imgPath = './static/img.jpg'
video = cv2.VideoCapture(videoPath)
status, frame = video.read()
cv2.imwrite(imgPath, frame)
# 压缩图片
img = open(imgPath, 'rb')
im = Image.open(img)
x, y = im.size
im.resize((int(x/10), int(y/10)))
im.save('./static/' + videoName + '.jpg')
# 关闭文件占用并清理缓存
video.release()
img.close()
os.remove(videoPath)
os.remove(imgPath)
# 输出结果
return json.dumps({
"code": 1,
"data": 'http://127.0.0.1:5000/static/' + videoName + '.jpg',
"msg": "请求成功"
})
if __name__ == '__main__':
CORS(app, supports_credentials=True)
app.run()
代码中未做文件验证和异常处理,仅写出了处理流程,请勿用于生产环境。
本文标签: 视频缩略图