为内存上传的视频文件生成缩略图

时间:2018-05-09 09:54:10

标签: django python-3.x ffmpeg

客户端应用上传了一个视频文件,我需要生成缩略图并将其转储到AWS s3,并将客户端链接返回到缩略图。 我四处搜索,发现 ffmpeg 符合此目的。 以下是我可以提出的代码:

from ffmpy import FFmpeg
import tempfile

def generate_thumbnails(file_name):
    output_file = tempfile.NamedTemporaryFile(suffix='.jpg', delete=False, prefix=file_name)
    output_file_path = output_file.name
    try:
        # generate the thumbnail using the first frame of the video
        ff = FFmpeg(inputs={file_name: None}, outputs={output_file_path: ['-ss', '00:00:1', '-vframes', '1']})
        ff.run()

        # upload generated thumbnail to s3 logic
        # return uploaded s3 path 
    except:
        error = traceback.format_exc()
        write_error_log(error)
    finally:
        os.remove(output_file_path)
    return ''

我正在使用 django ,并且上面提到了权限错误。 我发现晚于ffmpeg要求文件在磁盘上并且不仅仅考虑InMemory上传的文件(我可能错了,因为我假设这个)。

有没有办法在内存中使用ffmpeg 读取正常视频文件,或者我应该使用StringIO并将其转储到临时文件中。文件? 我不喜欢这样做,因为它是一种开销。

任何具有更好基准的替代解决方案也将受到赞赏。

感谢。

更新: 要将内存上传的文件保存到磁盘:How to copy InMemoryUploadedFile object to disk

1 个答案:

答案 0 :(得分:0)

我让它发挥作用的可能方式之一如下:

步骤:

a)通过chunk

将InMemory上传的文件读入临时文件块
temp_file = tempfile.NamedTemporaryFile(suffix='.mp4', delete=False)
temp_file_path = temp_file.name
with open(temp_file_path, 'wb+') as destination:
     for chunk in in_memory_file_content.chunks():
               destination.write(chunk)

b)使用ffmpeg和subprocess

生成缩略图
ffmpeg_command = 'ffmpeg -y -i {} -ss 00:00:01 vframes 1 {}'.format(video_file_path, thumbail_file_path                                                                                            
subprocess.call(ffmpeg_command, shell=True)

其中,

-y是覆盖目的地(如果它已经存在)

<00> 00:00:01是抓住第一帧

有关ffmpeg的更多信息:https://ffmpeg.org/ffmpeg.html