如何使用PIL在django中创建缩略图

时间:2015-02-19 12:46:35

标签: django python-imaging-library

当我的django模型被保存时,我试图创建一组已调整大小的图像。但是我在保存模型时遇到了错误 -

cannot identify image file <cStringIO.StringI object at 0x104558e88>

我的模型看起来像 -

class ProductImage(models.Model):
    extra_large_image = models.ImageField(upload_to='catalog/images',
                                          blank=True, null=True)
    main_image = models.ImageField("Main Image (max 460px high)",
                                   upload_to='catalog/images',
                                   blank=True, null=True)
    list_page_thumb = models.ImageField("thumbnail 220x220px",
                                   upload_to='catalog/images',
                                   blank=True, null=True)

    def duplicate_image(self, original_image_field, new_image_field, size):
        if original_image_field is None:
            print 'Cannot resize None things'
        else:
            IMG_TYPE = os.path.splitext(original_image_field.name)[1].strip('.')
            if IMG_TYPE == 'jpeg' or IMG_TYPE == 'jpg':
                PIL_TYPE = 'jpeg'
                FILE_EXTENSION = 'jpeg'
            elif IMG_TYPE == 'png':
                PIL_TYPE = 'png'
                FILE_EXTENSION = 'png'
            else:
                print 'Not a valid format'
                return

            im = Image.open(StringIO(original_image_field.read()))
            im.thumbnail(size, Image.ANTIALIAS)
            temp_handle = StringIO()
            im.save(temp_handle, PIL_TYPE)
            temp_handle.seek(0)
            suf = SimpleUploadedFile(os.path.split(original_image_field.name)[-1], temp_handle.read(), content_type=IMG_TYPE)
            size_text = str(size[0]) + "x" + str(size[1])
            new_image_field.save('%s_%s.%s' % (os.path.splitext(suf.name)[0],size_text,FILE_EXTENSION), suf, save=False)
        return


    def save(self, *args, **kwargs):
        if self.extra_large_image:
            self.duplicate_image(self.extra_large_image, self.main_image, (460,460))
            self.duplicate_image(self.extra_large_image, self.list_page_thumb, (220,220))
        self.date_modified = datetime.datetime.now()
        super(ProductImage, self).save(*args, **kwargs)

试图打开pil图像时会抛出错误 -

im = Image.open(StringIO(original_image_field.read()))

1 个答案:

答案 0 :(得分:0)

如果您想添加图片版本控制,我建议您使用django-imagekit。这是一个例子。

from django.db import models
from imagekit.models import ImageSpecField
from imagekit.processors import ResizeToFill

class Profile(models.Model):
    avatar = models.ImageField(upload_to='avatars')
    avatar_thumbnail = ImageSpecField(source='avatar',
                                      processors=[ResizeToFill(100, 50)],
                                      format='JPEG',
                                      options={'quality': 60})

在你的情况下,它会喜欢这个。

class ProductImage(models.Model):
    extra_large_image = models.ImageField(upload_to='catalog/images',
                                          blank=True, null=True)
    main_image = ImageSpecField(source="extra_large_image",
                                processors=[ResizeToFill(460, 460)],
                                format='JPEG',
                                          options={'quality': 60})
    list_page_thumb = ImageSpecField(source="extra_large_image",
                                     processors=[ResizeToFill(460, 460)],
                                     format='JPEG',
                                     options={'quality': 60})