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

View File

@@ -1,60 +1,28 @@
import mimetypes """
import os helpers.py
from typing import List, Tuple
from django.urls import reverse Contains helper functions used as refactored shortcuts or in order to separate code for readability.
"""
from viewer.models import ServedDirectory import cv2
from PIL import Image
class File: def generate_thumbnail(path: str, output_path: str) -> None:
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 Helper function which completes the process of generating thumbnails for both pictures and videos.
:param path: The path to the directory. :param path: The absolute path to the file.
:return: A list of tuples, each containing two strings, the file or directory name, and the media type. :param output_path: The absolute path to the intended output thumbnail file.
""" """
files = [] vidcap = cv2.VideoCapture(path)
for file in os.listdir(path): success, image = vidcap.read()
files.append(File(file, path)) if success:
return files 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))
def get_all_mediatype(head: str, tail: str) -> str: im_pil.save(output_path)
"""
A extra media type function supporting directories on top of files.
:param head: The head of the path, usually the directory name or filename at the very end.
:param tail: The rest of the path, everything that comes before the head.
:return: A media type in string form.
"""
if os.path.isfile(os.path.join(tail, head)):
return get_file_mediatype(head)
return "folder"