From d38c72e4d69101f22b9ef8f108faa0621b50d960 Mon Sep 17 00:00:00 2001 From: jr-k Date: Sat, 24 Aug 2024 20:53:45 +0200 Subject: [PATCH] lightweight dimensions detectors for pictures --- requirements.txt | 1 - src/util/UtilPicture.py | 133 ++++++++++++++++++++++++++++++++++++++-- 2 files changed, 129 insertions(+), 5 deletions(-) diff --git a/requirements.txt b/requirements.txt index 6e3b979..35696ad 100755 --- a/requirements.txt +++ b/requirements.txt @@ -6,4 +6,3 @@ waitress flask-login pysqlite3 psutil -pillow diff --git a/src/util/UtilPicture.py b/src/util/UtilPicture.py index be85a66..209de0e 100644 --- a/src/util/UtilPicture.py +++ b/src/util/UtilPicture.py @@ -1,8 +1,133 @@ import struct -from PIL import Image +import imghdr +import os + + +def get_png_size(file): + file.seek(16) + width, height = struct.unpack('>ii', file.read(8)) + return width, height + + +def get_jpeg_size(file): + file.seek(0) + size = 2 + ftype = 0 + while not 0xC0 <= ftype <= 0xCF: + file.seek(size, 1) + byte = file.read(1) + while ord(byte) == 0xFF: + byte = file.read(1) + ftype = ord(byte) + size = struct.unpack('>H', file.read(2))[0] - 2 + file.seek(1, 1) + height, width = struct.unpack('>HH', file.read(4)) + return width, height + + +def get_gif_size(file): + file.seek(6) + width, height = struct.unpack('> 6) | (b3 << 2) | ((b4 & 0x0F) << 10)) + 1 + return width, height + elif chunk_header[0:4] == b'VP8X': + vp8x_header = file.read(10) + width, height = struct.unpack(' largest_size[0] * largest_size[1]: + largest_size = (width, height) + file.seek(14, 1) # Skip over the rest of the directory entry + return largest_size def get_picture_metadata(image_path): - with Image.open(image_path) as img: - width, height = img.size - return width, height + # Determine the image type using imghdr and file extension as a fallback + img_type = imghdr.what(image_path) + if not img_type: + _, ext = os.path.splitext(image_path) + img_type = ext.lower().replace('.', '') + + with open(image_path, 'rb') as file: + if img_type == 'png': + return get_png_size(file) + elif img_type == 'jpeg' or img_type == 'jpg': + return get_jpeg_size(file) + elif img_type == 'gif': + return get_gif_size(file) + elif img_type == 'webp': + return get_webp_size(file) + elif img_type == 'bmp': + return get_bmp_size(file) + elif img_type == 'tiff' or img_type == 'tif': + return get_tiff_size(file) + elif img_type == 'ico': + return get_ico_size(file) + else: + raise ValueError("Unsupported image format or corrupted file")