使用imagekit创建视频缩略图并打开

2024-05-16 10:47:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个名为“Post”的模型,它将引用图像和视频。我为缩略图存储添加了ImageSpecField,并创建了一个函数,从上传的视频中提取所需的帧。在生成缩略图时有没有方法使用这个函数?因为现在ImageSpecField只能使用FileField作为输入。你知道吗

我试过创建一个从ImageSpecField继承的新类,但我很快意识到这是行不通的,因为这个类只在服务器启动时实例化过,因此将这个函数放到它的构造函数中是行不通的。你知道吗

import cv2 as cv
from django.conf import settings
from django.db import models
from imagekit.processors import ResizeToFit
from imagekit.models import ImageSpecField


def video_to_image(source, frame):
    vid_cap = cv.VideoCapture(settings.MEDIA_ROOT + source.__str__())
    vid_cap.set(cv.CAP_PROP_POS_FRAMES, frame)
    success, image = vid_cap.read()
    vid_cap.release()

    return image


class Post(models.Model):
    IMAGE = 'I'
    VIDEO = 'V'
    FILE_TYPES = [
        (IMAGE, 'Image'),
        (VIDEO, 'Video')
    ]

    file_type = models.CharField(max_length=1, choices=FILE_TYPES)
    file = models.FileField(upload_to='post_images')
    thumbnail_frame = models.IntegerField(default=0)
    image_thumbnail = ImageSpecField(source='file',
                                     processors=[ResizeToFit(width=200, height=200)],
                                     format='JPEG',
                                     options={'quality': 60})

我希望imagekit从视频生成缩略图,并能够通过ImageSpecField获得它。你知道吗


Tags: 函数fromimageimportsource视频modelsimagekit
1条回答
网友
1楼 · 发布于 2024-05-16 10:47:38

好吧,我想我终于明白了。我通过创建另一个字段-缩略图\源\图像并根据上载的文件类型执行以下操作来实现它:

  • 对于图像-将缩略图\源\图像设置为与文件字段相同的值
  • 对于视频-从给定的毫秒视频生成图像,将其保存到与文件相同的位置,并将其设置为缩略图\源\图像

我正在使用魔法库获取文件类型。你知道吗

但是这个方法有一个小问题——要让Django生成文件路径,我们必须在模型上调用save()方法。这迫使我们向数据库发出两个请求,而不是一个。你知道吗

你知道吗实用程序.py文件:

import cv2 as cv


def save_frame_from_video(video_path, millisecond, frame_file_path):
    vidcap = cv.VideoCapture(video_path)

    vidcap.set(cv.CAP_PROP_POS_MSEC, millisecond)

    success, image = vidcap.read()

    # save image to temp file
    cv.imwrite(frame_file_path, image)

    vidcap.release()

你知道吗型号.py文件:

import os
from django.conf import settings
from django.db import models
from imagekit.processors import ResizeToFit
from imagekit.models import ImageSpecField
from .utils import save_frame_from_video


class Post(models.Model):
    image_types = ['image/jpeg', 'image/gif', 'image/png']
    video_types = ['video/webm']

    IMAGE = 'I'
    VIDEO = 'V'
    TYPES = [
        (IMAGE, 'Image'),
        (VIDEO, 'Video'),
    ]

    type = models.CharField(max_length=1, choices=TYPES, blank=True)
    file = models.FileField(upload_to='post_files/%Y/%m/%d/')

    thumbnail_millisecond = models.IntegerField(default=0)
    thumbnail_source_image = models.ImageField(upload_to='post_files/%Y/%m/%d/', null=True, blank=True)
    image_thumbnail = ImageSpecField(source='thumbnail_source_image',
                                     processors=[
                                         ResizeToFit(150,
                                                     150,
                                                     mat_color=(230, 230, 230)),
                                     ],
                                     format='JPEG',
                                     options={'quality': 80})

    def _set_type(self):
        # max bytes to read for file type detection
        read_size = 5 * (1024 * 1024)  # 5MB

        # read mime type of file
        from magic import from_buffer
        mime = from_buffer(self.file.read(read_size), mime=True)

        if mime in self.image_types:
            self.type = self.IMAGE
        elif mime in self.video_types:
            self.type = self.VIDEO

    def _set_thumbnail_source_image(self):
        if self.type == self.IMAGE:
            self.thumbnail_source_image = self.file
        elif self.type == self.VIDEO:
            # create thumbnail source file
            image_path = os.path.splitext(self.file.path)[0] + '_thumbnail_src_image.jpg'
            save_frame_from_video(self.file.path, int(self.thumbnail_millisecond), image_path)

            # generate path relative to media root, because this is the version that ImageField accepts
            media_image_path = os.path.relpath(image_path, settings.MEDIA_ROOT)

            self.thumbnail_source_image = media_image_path

    def save(self, *args, **kwargs):
        if self.type == '':
            self._set_type()
        # if there is no source image
        if not bool(self.thumbnail_source_image):
            # we need to save first, for django to generate path for file in "file" field
            super().save(*args, **kwargs)
            self._set_thumbnail_source_image()

        super().save(*args, **kwargs)

相关问题 更多 >