将PIL.Image转换为wagtailimages.Image

问题描述 投票:0回答:2

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

Wagtail已经在使用Pillow,但我找不到一个简单的方法来做到这一点......

 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
python python-imaging-library wagtail
2个回答
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

0
投票

在看到gasman的答案之前,我成功完成了以下代码:

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)
© www.soinside.com 2019 - 2024. All rights reserved.