Sorl-thumbnail视图返回缩略图 - 没有模板标签

时间:2013-12-23 20:30:17

标签: python django performance thumbnails sorl-thumbnail

我对django中使用sorl-thumbnail生成的缩略图有疑问。

我的模特:

from django.db import models
from sorl.thumbnail import ImageField
from project.settings import UPLOAD_DIR

class MyImage(models.Model):
    file = ImageField(upload_to=UPLOAD_DIR)

我的观点:

from base.models import MyImage
from sorl.thumbnail import get_thumbnail
from django.http import HttpResponse
from project.settings import UPLOAD_DIR
from django.shortcuts import get_object_or_404

def thumbnail(request, filename, width, height):
    path = UPLOAD_DIR + '/' + filename
    image = get_object_or_404(MyImage, file=path)
    dim = '%sx%s' % (width, height)
    im = get_thumbnail(image.file, dim, crop='center', quality=90)
    return HttpResponse(im.read(), content_type='image/jpg')

并且网址:

from django.conf.urls import patterns, url
from base.views import thumbnail
from django.conf.urls.shortcut import urlpatterns

urlpatterns += patterns('',
    url(r'^100x100/(?P<filename>\S+)/$', thumbnail, {'width': 100, 'height':100, }),
)

它按预期工作,即它根据网址中给出的文件名动态生成缩略图。我需要它,因为我需要一种简单的方法来生成缩略图而不使用django标签。撰稿人使用简单的地址创建缩略图会更容易,例如:

<img src="/thumbnail/100x100/myimage.jpg" />

比:

{% thumbnail "http://mydomain.com/uploads/myimage.jpg" "100x100" crop="center" as im %}
    <img src="{{ im.url }}" />
{% endthumbnail %}

您如何看待这个想法?我应该在这段代码中更改什么?或者也许我应该尝试找到解决这个问题的其他方法?

0 个答案:

没有答案