开发者

Animated gif resizing with sorl-thumbnail

开发者 https://www.devze.com 2023-02-04 21:04 出处:网络
Is there any possibility to resize animate开发者_如何学Cd gifs with sorl?Wow, thats a feature request I would never expect! sorl.thumbnail is now engine configurable and comes with PIL and pgmagick. I

Is there any possibility to resize animate开发者_如何学Cd gifs with sorl?


Wow, thats a feature request I would never expect! sorl.thumbnail is now engine configurable and comes with PIL and pgmagick. I think there are ways to make imagemagick resize animated gifs and so maybe pgmagick can do this but I have not tested this and its very unlikely to work with the shipped engines as is.


I've got working solution (tested with sorl-thumbnail 11.12.1b). Requires Wand backend:

#sorl_extensions.py
from sorl.thumbnail.base import (
    ThumbnailBackend, EXTENSIONS,
    default_settings as thumbnail_default_settings
)


EXTENSIONS.update({'GIF': 'gif'})


class GifThumbnailBackend(ThumbnailBackend):
    def _get_format(self, file_):
        file_extension = self.file_extension(file_)

        if file_extension == '.jpg' or file_extension == '.jpeg':
            return 'JPEG'
        elif file_extension == '.png':
            return 'PNG'
        elif file_extension == '.gif':
            return 'GIF'
        else:
            from django.conf import settings

            return getattr(settings, 'THUMBNAIL_FORMAT', thumbnail_default_settings.THUMBNAIL_FORMAT)

#settings.py
THUMBNAIL_ENGINE = 'sorl.thumbnail.engines.wand_engine.Engine'
THUMBNAIL_BACKEND = 'tools.sorl_extensions.GifThumbnailBackend'
THUMBNAIL_PRESERVE_FORMAT = True


I managed to make sorl work with gif.

  1. You need to use image magick or graphics magick backend (PIL does not support gif resizing without some hacking). You can also try pgmagick, but I don't know if it will work.
  2. Put these somewhere in your code:

    from sorl.thumbnail import base
    base.EXTENSIONS.update({'GIF': 'gif'})
    

You can take a look at sorl-thumnail source to find how this works

UPD: It is untested. Use this only if you are sure about what you are doing.


I will share my example:

# -*- coding: utf-8 -*-
import os
from sorl.thumbnail import get_thumbnail

def get_file_extension(obj):
    filename, file_extension = os.path.splitext(obj)
    return file_extension

def get_thumbnail_size(obj, size):
    img_format = 'JPEG'
    if get_file_extension(obj.url) == '.png':
        img_format = 'PNG'
    if get_file_extension(obj.url) == '.gif':
        from sorl.thumbnail import base
        base.EXTENSIONS.update({'GIF': 'gif'})
        img_format = 'GIF'
    return get_thumbnail(obj, size, quality=90, format=img_format).url
0

精彩评论

暂无评论...
验证码 换一张
取 消