gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 23:25:33 26 4
gpt4 key购买 nike

客户端应用上传了一个视频文件,我需要 生成缩略图 并将其转储到 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

最佳答案

我让它工作的可能方法之一如下:

脚步:

a) 将 InMemory 上传的文件逐 block 读取到临时文件中

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 和子进程生成缩略图
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:01 是抓取第一帧

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

关于django - 为内存上传的视频文件生成缩略图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50250445/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com