簡體   English   中英

將PIL.Image轉換為wagtailimages.Image

[英]Converting a PIL.Image to wagtailimages.Image

我正在使用枕頭為圖像創建縮略圖,但是我無法將它們存儲在字段image_thumbnail中,因為該字段的類型為Image,並且我遇到了一個例外:ValueError:無法分配“”:“ GalleryItem.image_thumbnail”必須為一個“圖像”實例。

g已經在使用枕頭,但我找不到簡單的方法來做...

 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

從概念上講,PIL.Image和wagtailimages.Image是兩個不同的東西:PIL.Image表示一個圖像文件(即一堆特定的像素),而wagtailimages.Image是一個“圖片”的數據庫記錄,可以選擇並重用。編輯內容,並帶有支持的元數據(通常僅是標題,但其他字段也是可能的),並且能夠以任意大小重新呈現它。 使用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

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

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM