python - 使用 Django 调整图像大小?

标签 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

我现在遇到的问题是获取该文件并将新文件制作成缩略图。就像我说的,我想知道如何在不使用其他人的应用程序的情况下(暂时)做到这一点。我从 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?...)以及它如何在上下文中工作? ...我只需要一点帮助来理解和解决这个问题。

谢谢!

最佳答案

如果您觉得合适,已经准备好一个 Django 应用程序,它可以完全满足您的需求: https://github.com/sorl/sorl-thumbnail

关于python - 使用 Django 调整图像大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1164930/

相关文章:

python - 如何将 HTML block (使用 python)插入当前工作的网站....?

django - 在 Django 中动态删除内联表单集

javascript - 如何根据django admin中的另一个选择字段限制选择字段选项

linux - ffmpeg - 忽略第一张图像的图像集中的幻灯片

javascript - 如何使用 Angular.js 添加裁剪图像

python - 没有线程安全的优先级队列

python矩阵转置和zip

python - 将列表元素作为函数的参数一一传递

python - 通过 AJAX 将 Python 数组发送到 django 模板

python 图像 PIL 到二进制十六进制