将PIL.Image转换为wagtailimages.Image

时间:2018-08-27 10:56:43

标签: python python-imaging-library wagtail

我正在使用Pillow为图像创建缩略图,但是我无法将它们存储在image_thumbnail字段中,因为该字段是Image类型,并且我遇到了一个例外:ValueError:无法分配“”:“ GalleryItem.image_thumbnail ”必须是“图片”实例。

Wagtail已经在使用枕头,但是我找不到简单的方法...

 class GalleryItem(models.Model):
    image = models.ForeignKey(
        'wagtailimages.Image',
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name='+',
        help_text='Image size must be 1440 x 961 px.'
    )
    image_thumbnail = models.ForeignKey(
        'wagtailimages.Image',
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name='+',
    )
    category = models.ForeignKey(
        'ImageCategorie',
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name='+'
    )

    def createThumbnails(self):
        size = (300, 300)
        outfile = self.image.title.split('.')[0] + ".thumbnail.jpg"
        try:
            im = Image.open(self.image.file)
            im.thumbnail(size)
            im.save(outfile, format="jpeg")
            return im
        except IOError:
            print("cannot create thumbnail for", self.image.file)

    def save(self, *args, **kwargs):
        self.image_thumbnail = self.createThumbnails()
        import ipdb; ipdb.set_trace()
        super(GalleryItem, self).save(*args, **kwargs)

    def __str__(self):
        return self.image.title

2 个答案:

答案 0 :(得分:2)

从概念上讲,PIL.Image和wagtailimages.Image是两个不同的东西:PIL.Image表示图像文件(即特定的一堆像素),而wagtailimages.Image是“图片”的数据库记录。可选且可重复使用的编辑内容,并带有支持的元数据(通常仅是标题,但是other fields也是可能的),并且能够以任何大小重新呈现它。使用wagtailimages.Image存储现有图像的缩略图版本是过大的选择,最好将image_thumbnail字段设置为Django ImageField(将图像存储在“像素束”中)感。)

如果您真的想在此处使用wagtailimages.Image,可以,但是您需要为该图像创建数据库记录,然后然后将其附加到GalleryItem对象。该代码将类似于:

from io import BytesIO

from PIL import Image as PILImage
from django.core.files.images import ImageFile
from wagtail.images.models import Image as WagtailImage

...
    pil_image = PILImage.open(self.image.file)
    pil_image.thumbnail(size)
    f = BytesIO()
    pil_image.save(f, 'JPEG')

    wagtail_image = WagtailImage.objects.create(
        title=('thumbnail of %s' % self.image.title),
        file=ImageFile(f, name=outfile)
    )
    self.image_thumbnail = wagtail_image

答案 1 :(得分:0)

在看到加斯曼的答案之前,我成功编写了以下代码:

def createThumbnails(self):
        # Set our max thumbnail size in a tuple (max width, max height)
        THUMBNAIL_SIZE = (200, 200)
        outfile = self.image.title.split('.')[0] + ".thumbnail.jpg"
        extention = self.image.filename.split('.')[1]
        img_io = BytesIO()
        PIL_TYPE = 'jpeg'
        try:
            # Open original photo which we want to thumbnail using PIL's Image
            im = PILImage.open(BytesIO(self.image.file.read()))
            im.thumbnail(THUMBNAIL_SIZE, PILImage.ANTIALIAS)
            im.save(img_io, PIL_TYPE)
            img_io.seek(0)
            # Save image to a SimpleUploadedFile which can be saved into
            # ImageField
            suf = SimpleUploadedFile(outfile, img_io.read())
            self.screenshot.save(outfile, suf, save=False)
        except IOError:
            print("cannot create thumbnail for", self.image.file)

    def save(self, *args, **kwargs):
        self.createThumbnails()
        super(GalleryItem, self).save(force_update=False)