我是 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
我现在遇到的问题是获取该文件并将新文件制作成缩略图。就像我说的,我想知道如何在不使用其他应用程序的情况下做到这一点(目前)。我从 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'
...但这最终使我感到困惑...因为我不知道这如何“适合”我的 Django 应用程序?真的,它是简单地为已成功上传的图像制作缩略图的最佳解决方案吗?任何人都可以向我展示一个像我这样的初学者可以学会正确地做到这一点的好方法吗?例如,知道将那种代码(models.py?forms.py?...)放在哪里以及它在上下文中如何工作?...我只需要一些帮助来理解和解决这个问题。
谢谢!