basic cv2 & PIL based thumbnail generation helper

This commit is contained in:
Xevion
2020-10-31 22:47:10 -05:00
parent d565e82c50
commit 176b3273ce
+20 -52
View File
@@ -1,60 +1,28 @@
import mimetypes
import os
from typing import List, Tuple
from django.urls import reverse
from viewer.models import ServedDirectory
class File:
def __init__(self, head, tail):
self.filename = head
self.fullpath = os.path.join(tail, head)
self.mediatype = self.get_mediatype()
def get_url(self, directory: ServedDirectory) -> str:
return reverse('file', args=(directory.id, self.filename))
def get_mediatype(self) -> str:
"""Simple media type categorization based on the given mimetype"""
if os.path.exists(self.fullpath):
if os.path.isdir(self.fullpath):
return 'folder'
mimetype = mimetypes.guess_type(self.filename)[0]
if mimetype is not None:
if mimetype.startswith('image'):
return 'image'
elif mimetype.startswith('video'):
return 'video'
return 'file'
return 'unknown'
def __str__(self) -> str:
return self.filename
def extra_listdir(path: str) -> List[File]:
""" """
Helper function used for identifying file media type for every file in a given directory, extending os.listdir helpers.py
:param path: The path to the directory. Contains helper functions used as refactored shortcuts or in order to separate code for readability.
:return: A list of tuples, each containing two strings, the file or directory name, and the media type.
""" """
files = [] import cv2
for file in os.listdir(path): from PIL import Image
files.append(File(file, path))
return files
def get_all_mediatype(head: str, tail: str) -> str: def generate_thumbnail(path: str, output_path: str) -> None:
""" """
A extra media type function supporting directories on top of files. Helper function which completes the process of generating thumbnails for both pictures and videos.
:param head: The head of the path, usually the directory name or filename at the very end. :param path: The absolute path to the file.
:param tail: The rest of the path, everything that comes before the head. :param output_path: The absolute path to the intended output thumbnail file.
:return: A media type in string form.
""" """
if os.path.isfile(os.path.join(tail, head)): vidcap = cv2.VideoCapture(path)
return get_file_mediatype(head) success, image = vidcap.read()
return "folder" if success:
img = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
im_pil = Image.fromarray(img)
# Resize, crop, thumbnail
im_pil.thumbnail((300, 300))
# im_pil.crop((0, 0, 200, 66))
# im_pil.resize((200, 66))
im_pil.save(output_path)