使用django调整图像大小?

lit*_*m84 12 python django image python-imaging-library

我是Django(和Python)的新手,在开始使用其他人的应用程序之前,我一直在尝试自己解决一些问题.我无法理解Django(或Python)的工作方式中的"适合".我正在尝试解决的是如何在上传图像后调整图像大小.我很好地安装了我的模型并插入管理员,图像上传到目录:

from django.db import models

# This is to list all the countries
# For starters though, this will be just United Kingdom (GB)
class Country(models.Model):
    name = models.CharField(max_length=120, help_text="Full name of country")
    code = models.CharField(max_length=2, help_text="This is the ISO 3166 2-letter country code (see: http://www.theodora.com/country_digraphs.html)")
    flag = models.ImageField(upload_to="images/uploaded/country/", max_length=150, help_text="The flag image of the country.", blank=True)

    class Meta:
        verbose_name_plural = "Countries"

    def __unicode__(self):
        return self.name
Run Code Online (Sandbox Code Playgroud)

我现在遇到的问题是获取该文件并将新文件制作成缩略图.就像我说的,我想知道如何在不使用别人的应用程序的情况下(现在).我从DjangoSnippets获得了这段代码:

from PIL import Image
import os.path
import StringIO

def thumbnail(filename, size=(50, 50), output_filename=None):
    image = Image.open(filename)
    if image.mode not in ('L', 'RGB'):
        image = image.convert('RGB')
    image = image.resize(size, Image.ANTIALIAS)

    # get the thumbnail data in memory.
    if not output_filename:
        output_filename = get_default_thumbnail_filename(filename)
    image.save(output_filename, image.format) 
    return output_filename

def thumbnail_string(buf, size=(50, 50)):
    f = StringIO.StringIO(buf)
    image = Image.open(f)
    if image.mode not in ('L', 'RGB'):
        image = image.convert('RGB')
    image = image.resize(size, Image.ANTIALIAS)
    o = StringIO.StringIO()
    image.save(o, "JPEG")
    return o.getvalue()

def get_default_thumbnail_filename(filename):
    path, ext = os.path.splitext(filename)
    return path + '.thumb.jpg'
Run Code Online (Sandbox Code Playgroud)

...但这最终让我感到困惑......因为我不知道这对我的Django应用程序有什么影响?真的,它是简单地制作已成功上传的图像缩略图的最佳解决方案吗?任何人都可以向我展示一个好的,坚实的,体面的方式,像我这样的初学者可以学会正确地做到这一点吗?就像在,知道在哪里放置那种代码(models.py?forms.py?...)以及它如何在上下文中工作?......我只是需要一些帮助来理解并解决这个问题.

谢谢!

lea*_*ode 7

如果你没问题,那就准备好了一个Django应用程序,正是你想要的:https: //github.com/sorl/sorl-thumbnail

  • 谢谢leafnode,我听说过这个,我会看一下.但我希望首先尝试理解做事的基本方法,希望能让我更好地理解这一切是如何运作的......也许这不值得这样做?...但我认为这样做是值得的让我成为更好的Python/Django开发人员? (2认同)