From 3029eea1a041ea46c0f1ac586d8f408d61c43281 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9DNyymix=E2=80=9D?= Date: Fri, 11 Apr 2025 22:15:25 +0300 Subject: [PATCH] Add width & height data to thumbnails --- gallery/models/album.py | 39 +++++++++++++++++++---- gallery/templates/gallery/album_list.html | 8 +++-- gallery/templates/gallery/search.html | 8 +++-- 3 files changed, 42 insertions(+), 13 deletions(-) diff --git a/gallery/models/album.py b/gallery/models/album.py index bfc0e4b..f7ab1a8 100644 --- a/gallery/models/album.py +++ b/gallery/models/album.py @@ -1,4 +1,5 @@ from datetime import datetime +from math import floor from django.core.exceptions import ValidationError from django.db import models @@ -27,13 +28,37 @@ class Album(models.Model): return total_views @property - def cover_url(self): - if self.cover: - return self.cover.photo_md.url - random_cover = self.photos.order_by('-width').first() - if random_cover: - return random_cover.photo_md.url - return static('img/placeholder.png') + def cover_image_data(self): + def compute_size(photo, max_w=720, max_h=720): + if not photo.width or not photo.height: + return (None, None) + aspect = photo.aspect_ratio + if photo.width > photo.height: + w = min(photo.width, max_w) + h = floor(w / aspect) + else: + h = min(photo.height, max_h) + w = floor(h * aspect) + return (w, h) + + photo = self.cover or self.photos.order_by('-width').first() + if photo: + url = photo.photo_md.url + w, h = compute_size(photo) + return { + "url": url, + "width": w, + "height": h, + "aspect_ratio": round(photo.aspect_ratio, 3) + } + + return { + "url": static('img/placeholder.png'), + "width": 1200, + "height": 800, + "aspect_ratio": 1.5 + } + def save(self, *args, **kwargs): if not self.slug: diff --git a/gallery/templates/gallery/album_list.html b/gallery/templates/gallery/album_list.html index 9b5a05c..c204fb6 100644 --- a/gallery/templates/gallery/album_list.html +++ b/gallery/templates/gallery/album_list.html @@ -29,10 +29,12 @@
- Cover image for {{ album.name }}
diff --git a/gallery/templates/gallery/search.html b/gallery/templates/gallery/search.html index 1614564..530ff11 100644 --- a/gallery/templates/gallery/search.html +++ b/gallery/templates/gallery/search.html @@ -29,10 +29,12 @@
- Cover image for {{ album.name }}