徐向博 / Imin.

Python 生成视频缩略图
作者:Imin 时间:2021-11-05 分类: 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()

代码中未做文件验证和异常处理,仅写出了处理流程,请勿用于生产环境。


本文标签: 视频缩略图

250075083: 必须顶的。。。。。。。。。 2022-08-08 05:55
自媒体平台: 博客很棒  欢迎回访我哦 2021-11-30 12:30