Add width & height data to thumbnails

This commit is contained in:
Nyymix 2025-04-11 22:15:25 +03:00
parent 6ac75c50c6
commit 3029eea1a0
3 changed files with 42 additions and 13 deletions

View file

@ -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:

View file

@ -29,10 +29,12 @@
<!-- Album cover image -->
<div class="uk-card-media-top">
<a href="{{ album.get_absolute_url }}">
<img src="{{ album.cover_url }}"
style="aspect-ratio: {{ album.cover.aspect_ratio }};"
<img src="{{ album.cover_image_data.url }}"
width="{{ album.cover_image_data.width }}"
height="{{ album.cover_image_data.height }}"
style="aspect-ratio: {{ album.cover_image_data.aspect_ratio }};"
alt="Cover image for {{ album.name }}"
title="{{ album.name }}"
title="{{ album.name }}"
loading="lazy">
</a>
</div>

View file

@ -29,10 +29,12 @@
<!-- Album cover image -->
<div class="uk-card-media-top">
<a href="{{ album.get_absolute_url }}">
<img src="{{ album.cover_url }}"
style="aspect-ratio: {{ album.cover.aspect_ratio }};"
<img src="{{ album.cover_image_data.url }}"
width="{{ album.cover_image_data.width }}"
height="{{ album.cover_image_data.height }}"
style="aspect-ratio: {{ album.cover_image_data.aspect_ratio }};"
alt="Cover image for {{ album.name }}"
title="{{ album.name }}"
title="{{ album.name }}"
loading="lazy">
</a>
</div>