Auto generate thumbnail for FileField in django
I uploaded different file types to my project(pdf,doc,mp4 ,jpg). now I want to auto-generate thumbnail for each file which is going to add or was added previously, and save it to my DB. here is what I think: here is my File model:
class File(models.Model):
slug = models.SlugField(
max_length=255,
unique=True,
)
address = models.FileField(
validators=[
file_size,
FileExtensionValidator(
allowed_extensions=[
"jpg",
"mp4",
"doc",
"pdf",
]
),
],
upload_to="files/",
max_length=255,
)
thumbnail = models.ImageField(
upload_to="files/thum/", max_length=255, null=True, blank=True
)
TYPES = [
(IMG, "Image"),
(VID, "Video"),
(DOC, "Document"),
]
type = models.CharField(max_length=3, choices=TYPES, default=IMG)
here I wrote a function :
from io import StringIO
from PIL import Image
def make_thumbnail(file):
if file.type == File.IMG:
make_image_thumbnail(file)
if file.type == File.VID:
make_video_thumbnail(file)
if file.type == File.DOC:
make_document_thumbnail(file)
def make_image_thumbnail(file):
img = Image.open(file.address)
img.thumbnail((128, 128), Image.ANTIALIAS)
thumbnailString = StringIO()
img.save(thumbnailString, "JPEG")#error : string argument expected, got 'bytes'
newFile = InMemoryUploadedFile(
thumbnailString, None, "temp.jpg", "image/jpeg", thumbnailString.len, None
)
return newFile
def make_video_thumbnail(file):
video_input_path = file.address
file_name = file.slug + "thumbnail"
img_output_path = os.path.join(settings.MEDIA_ROOT, file_name)
subprocess.call(
[
"ffmpeg",
"-i",
video_input_path,
"-ss",
"00:00:00.000",
"-vframes",
"1",
img_output_path,
]
)
def make_document_thumbnail(file):
# cache_path = ?
# pdf_or_odt_to_preview_path = file.address
# manager = PreviewManager(cache_path, create_folder=True)
# path_to_preview_image = manager.get_jpeg_preview(pdf_or_odt_to_preview_path)
pass
now I want to fill the functions and I don't know a) how can I auto-generate it b) how can I generate thumbnail for image and doc?( I tested these libs but I was confused totally) preview-generator and also django-thumbnails (for the files which I added I planed to write a migration and run it. is there any better idea?)