iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 26
0
Modern Web

加速你的 Django 網站開發 - Django 的好用套件系列 第 26

26. easy-thumbnails

該不該縮圖?縮圖尺寸能不能有彈性一點?可以由前端來指定縮圖尺寸嗎?在網站開發時,經常會碰到這些糾結的問題,easy-thumbnails 最主要的功能就和他的名字一樣,簡化了縮圖的操作。

專案網址:https://easy-thumbnails.readthedocs.io/en/latest/index.html

安裝

poetry add easy-thumbnails

設定

# settings
INSTALLED_APPS = [
    ...
    'easy_thumbnails',
]

THUMBNAIL_ALIASES = {
    '': {
        'avatar': {'size': (50, 50), 'crop': True, 'quality': 90},
    },
}

最主要的設定就是在 INSTALLED_APPS 加入 easy_thumbnails

THUMBNAIL_ALIASES 則是用來設定別名以提供快速設定,像上面的 'avatar' 就表示尺寸是 50x50,要裁減,所以後續程式指定要使用 avatar 時,就會使用 50x50 這尺寸,並且進行裁減。

使用

在 template 裡使用,必須要載入 thumbnail ,裡面包含了 easy_thumbnails 的 tag 跟 filter。

{# template #}
{% load thumbnail %}
<img src="{{ profile.photo|thumbnail_url:'avatar' }}" alt="" />

像上面的例子就是使用 filter ,同時也指定使用 avatar 這個別名。

<img src="{% thumbnail profile.photo 120x120 crop %}" alt="" />

也可以直接呼叫 thumbnail 來處理,上面的例子就不使用別名,而是直接指定尺寸跟是否裁減。

在 View 裡也可以直接使用 get_thumbnailer 來處理。

from easy_thumbnails.files import get_thumbnailer
thumb_url = get_thumbnailer(profile.photo)['avatar'].url

上面的例子就是以 get_thumbnailer 去處理 profile.photo ,並套用 avatar 這個別名。

from easy_thumbnails.files import get_thumbnailer
options = {'size': (100, 100), 'crop': True}
thumb_url = get_thumbnailer(profile.photo).get_thumbnail(options).url

同樣的,也可以使用 dict 來自訂尺寸跟是否裁減,再傳遞給 get_thumbnail 。

其實,如果 model 裡有 ImageField 又有縮圖需求的話,可以將 ImageField 改為 ThumbnailerImageField:

# models
from easy_thumbnails.fields import ThumbnailerImageField

class Profile(models.Model):
    user = models.OneToOneField('auth.User')
    photo = ThumbnailerImageField(upload_to='photos', blank=True)

改用 thumbnailerImageField ,上傳圖片還是跟 ImageField 一樣,但是在使用時,可以直接透過屬性取得縮圖,就不需要再使用 template filter 或是用程式產生了:

{% load thumbnail %}
<img src="{{ profile.photo.avatar.url }}" alt="" />

程式裡使用:

thumb_url = profile.photo['avatar'].url

結語

easy_thumbnails 簡化了許多操作縮圖的步驟,使用上輕鬆許多。easy_thumbnails 的底層使用 pillow,pillow 是一套強大的函式庫,用來處理圖形,如果需要更細部的圖像處理,可以參考 pillow 來做。


上一篇
25. django-q
下一篇
27. django-authtools
系列文
加速你的 Django 網站開發 - Django 的好用套件30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言