Задать вопрос

Тел: +7 965 3737 888

521

Просмотров

4

Ответов

Dynamic thumbnail generator

<p>This snippet creates thumbnails on-demand from a ImageField with any size using dynamics methods, like get_photo_80x80_url or get_photo_640x480_filename, etc.</p>
<p>It assumes you have an ImageField in your Model called photo and have this in your models.py:</p>
import re

from os import path
from PIL import Image

GET_THUMB_PATTERN = re.compile(r'^get_photo_(\d+)x(\d+)_(url|filename)$')

<p>models.py example:</p>
import re

from os import path
from PIL import Image
from django.db import models

GET_THUMB_PATTERN = re.compile(r'^get_photo_(\d+)x(\d+)_(url|filename)$')

class Photo(models.Model):
    photo = models.ImageField(upload_to='photos/%Y/%m/%d')

    &lt;snippet here&gt;

<p>Example usage:</p>
&gt;&gt;&gt; photo = Photo(photo="/tmp/test.jpg")
&gt;&gt;&gt; photo.save()
&gt;&gt;&gt; photo.get_photo_80x80_url()
u"http://media.example.net/photos/2008/02/26/test_80x80.jpg"
&gt;&gt;&gt; photo.get_photo_80x80_filename()
u"/srv/media/photos/2008/02/26/test_80x80.jpg"
&gt;&gt;&gt; photo.get_photo_64x64_url()
u"http://media.example.net/photos/2008/02/26/test_64x64.jpg"
&gt;&gt;&gt; photo.get_photo_64x64_filename()
u"/srv/media/photos/2008/02/26/test_64x64.jpg"

Вопрос полезен? Да0/Нет0
file_2535.py(1.4Кб)
None

Ответы (4):

Ответbenjaoming:03.08.2008
Ответ полезен? Да0/Нет0

In order to automatically clean up old thumbs when a new picture is saved:

def save(self):
    # Delete thumbnails
    import glob, os
    file, ext = path.splitext(self.get_image_filename())
    pattern = file.rstrip("_") + "*x*" + ext
    thumbs = glob.glob(pattern)
    for thumb in thumbs:
        print thumb
        os.remove(thumb)

    super(GalleryImage, self).save()

Ответandrewingram:01.03.2008
Ответ полезен? Да0/Нет0

Is it possible to make it delete the generated images if the parent field is edited or deleted?

Ответandrewingram:27.02.2008
Ответ полезен? Да0/Нет0

Nice, I can see this coming in very handy and it's a lot more straightforward than I expected it to be (a testament to the very powerful features and libraries of Python).

Ответsemente:27.02.2008
Ответ полезен? Да0/Нет0

Fixed a bug:

<<<    size = width, height
>>>    size = int(width), int(height)