13

我是 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?...)放在哪里以及它在上下文中如何工作?...我只需要一些帮助来理解和解决这个问题。

谢谢!

4

12 回答 12

9

如果你没问题,有一个 Django 应用程序已经准备好了,可以做你想做的事: https ://github.com/sorl/sorl-thumbnail

于 2009-07-22T12:43:47.450 回答
4

如果上传的图像发生变化,这就是我在模型中用来保存新缩略图的方法。它基于另一个 DjangoSnippet,但我不记得是谁写了原版 - 如果你知道,请添加评论,以便我可以信任他们。

from PIL import Image
from django.db import models
from django.contrib.auth.models import User

import os
import settings

class Photo_Ex(models.Model):
    user = models.ForeignKey(User, blank=True, null=True)    
    photo = models.ImageField(upload_to='photos')
    thumbnail = models.ImageField(upload_to='profile_thumb', blank=True,
                              null=True, editable=False)

    def save(self, *args, **kwargs):
        size = (256,256)
        if not self.id and not self.photo:
            return

        try:
            old_obj = Photo_Ex.objects.get(pk=self.pk)
            old_path = old_obj.photo.path
        except:
            pass

        thumb_update = False
        if self.thumbnail:
            try:
                statinfo1 = os.stat(self.photo.path)
                statinfo2 = os.stat(self.thumbnail.path)
                if statinfo1 > statinfo2:
                    thumb_update = True
            except:
                thumb_update = True

        pw = self.photo.width
        ph = self.photo.height
        nw = size[0]
        nh = size[1]

        if self.photo and not self.thumbnail or thumb_update:
            # only do this if the image needs resizing
            if (pw, ph) != (nw, nh):
                filename = str(self.photo.path)
                image = Image.open(filename)
                pr = float(pw) / float(ph)
                nr = float(nw) / float(nh)

                if image.mode not in ('L', 'RGB'):
                    image = image.convert('RGB')

                if pr > nr:
                    # photo aspect is wider than destination ratio
                    tw = int(round(nh * pr))
                    image = image.resize((tw, nh), Image.ANTIALIAS)
                    l = int(round(( tw - nw ) / 2.0))
                    image = image.crop((l, 0, l + nw, nh))
                elif pr < nr:
                    # photo aspect is taller than destination ratio
                    th = int(round(nw / pr))
                    image = image.resize((nw, th), Image.ANTIALIAS)
                    t = int(round(( th - nh ) / 2.0))
                    image = image.crop((0, t, nw, t + nh))
                else:
                    # photo aspect matches the destination ratio
                    image = image.resize(size, Image.ANTIALIAS)

            image.save(self.get_thumbnail_path())
            (a, b) = os.path.split(self.photo.name)
            self.thumbnail = a + '/thumbs/' + b
            super(Photo_Ex, self).save()
            try:
                os.remove(old_path)
                os.remove(self.get_old_thumbnail_path(old_path))
            except:
                pass

    def get_thumbnail_path(self):
        (head, tail) = os.path.split(self.photo.path)
        if not os.path.isdir(head + '/thumbs'):
            os.mkdir(head + '/thumbs')
        return head + '/thumbs/' + tail

    def get_old_thumbnail_path(self, old_photo_path):
        (head, tail) = os.path.split(old_photo_path)
        return head + '/thumbs/' + tail   
于 2009-07-22T13:39:22.650 回答
3

不确定您发送的代码,因为我从不使用模型,但还有另一种方法。

您可以实现自己FileUploadHandler的处理图像文件上传。例子在 这里。就在第 37 行 ( dest.close()) 之后使用thumbnail(upload_dir + upload.name)函数(您发送的那个)。

希望它可以帮助你。

于 2009-07-22T12:44:10.523 回答
2

一个关键问题是:什么时候应该生成缩略图?

  1. 当用户请求缩略图时动态?
  2. 或者您是否想在数据库中插入/更新一个国家/地区时创建一个物理磁盘文件。

如果 (1) 我建议您创建一个映射到 url 的视图/flagthumbnail/countryid。然后视图方法必须:

  1. 从数据库中获取国家实例
  2. 将标志图像读入 PIL 图像并调整其大小。
  3. 创建(并返回)具有正确内容类型的 HTTPResponse,并将 PIL Image 写入响应。

每当您需要显示缩略图标志时,只需使用<a href="/flagthumbnail/countryid">.

如果 (2),您可以连接到 Django 的django.db.models.signals.post_save信号并在信号处理程序中创建并保存缩略图文件。

于 2009-07-22T12:51:25.703 回答
2

我想这取决于您使用缩略图的方式和时间。

如果您想在每次保存国家/地区时创建一些缩略图,您可以这样做:

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

    def save(self, force_insert=False, force_update=False):
        resize_image(self.flag)
        super(Country, self).save(force_insert, force_update)

如果您不能 100% 确定您需要什么样的图像尺寸,您可以在最后一分钟调整它们的大小。我已经看到使用模板标签有效地完成了这一点(我相信 Pinax 上的一个版本)。您创建一个模板标签来获取图像和大小,然后根据需要创建并保存适当大小的图像,或者显示先前创建的图像(如果存在)。它工作得很好。

于 2009-07-22T13:00:26.300 回答
2

覆盖 save 方法是一个不错的选择,但在这种情况下我更倾向于使用信号。Django 信号允许你“监听”给定模型类型的各种事件;在这种情况下,您会对该post_save事件感兴趣。

models.py我通常在我的文件中订阅此类信号。你的代码看起来像这样:

from django.db.models.signals import post_save
from models import Country

def resize_image(sender, **kwargs):
    country = kwargs["instance"]
    resize_image(country.flag) # where resize_image generates a thumbnail given a Country instance

post_save.connect(resize_image, sender=Country)
于 2009-07-22T14:03:32.433 回答
2

您可以尝试:

图像头像

特征:

  • 允许您设置图像的注意力中心......头部不会再被切割。
  • 视频缩略图
  • 防止跨站点图像链接
  • 简单的设置和使用
于 2011-06-12T10:49:44.207 回答
1

Ryan 是正确的信号是一种更好的方法,但是覆盖保存的优点是我们可以获取新旧图像路径,查看图像是否已更改(以及是否创建了新缩略图),保存模型实例然后删除旧图像和缩略图。

请记住,django 不会为您清理旧图像,因此除非您有脚本来检查图像/缩略图是否仍在使用中并清除任何不使用的图像,否则您将泄漏磁盘空间。(这对您来说可能是也可能不是问题,具体取决于图像大小和更新频率)

我不确定你如何使用 post_save 信号来做到这一点,而且我对信号的了解还不够(这是今晚的研究!)知道是否有合适的 pre_save 信号。如果我找到了,那么我将重写上面的代码以将信号用作通用的预保存侦听器。

于 2009-07-22T15:01:54.353 回答
1

另一种选择是直接使用 Imagemagick,如果你想避免 Pillow 和 Python 3 的一些困难,比如这个

from subprocess import call
call(['convert', img_path_file_name, '-thumbnail', target_size_str, '-antialias', style_path_file_name])

您可以在模型保存或模板标签上调用它,以文件缓存方式生成原始文件的一次性操作副本,甚至是 celery 任务。

你可以得到一个例子,说明我是如何在我的一个项目中使用它的:

于 2016-04-18T14:54:54.213 回答
0

我还发誓 Justin Driscoll 的django-photologue也非常适合调整大小。它:

  1. 调整大小(即可以按比例缩放到高度或宽度)
  2. 作物(一种智能:从中心、顶部、左侧、底部或右侧)
  3. 可选择升迁
  4. 可以添加效果(例如“颜色”、“亮度”、“对比度”和“锐度”以及“查找边缘”和“浮雕”等滤镜。锐化图像。让缩略图变成黑白。)
  5. 可以添加简单的水印
  6. 缓存结果

基本上它很棒。

于 2009-08-26T15:51:36.813 回答
0

一个非常简单的方法是使用django-imagefit调整和/或裁剪显示的图像。

它将保留原始图像,因此您可以拥有多个版本,稍后重构您的前端,并且它也适用于非模型图像。

于 2018-03-27T08:30:27.333 回答
-1

您可以使用 'Pillow' 在数据库模型中保存数据后更改照片大小,例如,我要将用户个人资料图像更改为 300 x 300,我将在模型中定义 save() 方法并更改大小,只需遵循以下步骤:

1-首先确保安装了“枕头”。

2-这是我在配置文件模型类中的代码:

from PIL import Image

class Profile(models.Model):

    PRF_image = models.ImageField(upload_to='profile_img', blank=True, null=True)



    def save(self , *args , **kwargs):
        # change profile image size
        img = Image.open(self.PRF_image.path)
        if img.width > 300 or img.height > 300:
            output_size = (300, 300)
            img.thumbnail(output_size)
            img.save(self.PRF_image.path)

这只是示例,并根据您的情况/要求进行更改。

并且不要忘记在视图中使用 your_object.save() 来使用此方法。

我希望这有帮助

于 2020-09-22T10:19:49.907 回答