将通过PIL创建的图像保存到django模型

时间:2011-06-15 15:04:09

标签: python django django-models python-imaging-library

我已使用以下代码成功创建并旋转了通过电子邮件上传到我服务器上的目录的图像:

      image = ContentFile(b64decode(part.get_payload()))
      im = Image.open(image)
      tempfile = im.rotate(90)
      tempfile.save("/srv/www/mysite.com/public_html/media/images/rotate.jpg", "JPEG")
      img = Photo(user=user)
      img.img.save('rotate.jpg', tempfile)
      img.save()

旋转的图像存在于目录中,但是当我尝试将该图像添加到我的模型时,它不会保存。我错过了什么?任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:16)

我用以下代码解决了这个问题:

       image = ContentFile(b64decode(part.get_payload()))
       im = Image.open(image)
       tempfile = im.rotate(270)
       tempfile_io =StringIO.StringIO()
       tempfile.save(tempfile_io, format='JPEG')
       image_file = InMemoryUploadedFile(tempfile_io, None, 'rotate.jpg','image/jpeg',tempfile_io.len, None)
       img = Photo(user=user)
       img.img.save('rotate.jpg', image_file)
       img.save()

我在这里找到了答案How do you convert a PIL `Image` to a Django `File`?。完美无瑕地工作!!!

答案 1 :(得分:0)

from django.db import models
from .abstract_classes import DateTimeCreatedModified
from PIL import Image
from io import BytesIO
from django.core.files.base import ContentFile
from enum import Enum

class MediaSize(Enum):
    #             size       base file name
    DEFAULT = ((1080, 1080), 'bus_default')
    MEDIUM = ((612, 612), 'bus_medium')
    THUMBNAIL = ((161, 161), 'bus_thumbnail')


class Media(DateTimeCreatedModified):

    # The original image.
    original = models.ImageField()
    # Resized images...
    default = models.ImageField()
    medium = models.ImageField()
    thumbnail = models.ImageField()




    def resizeImg(self, img_size):
        img: Image.Image = Image.open(self.original)
        img.thumbnail(img_size, Image.ANTIALIAS)

        outputIO = BytesIO()
        img.save(outputIO, format=img.format, quality=100)

        return outputIO, img


    def handleResize(self, mediaSize: MediaSize):

        imgSize = mediaSize.value[0]
        imgName = mediaSize.value[1]

        outputIO, img = self.resizeImg(imgSize)

        return {
            # Files aren't be overwritten
            # because `AWS_S3_FILE_OVERWRITE = False`
            # is set in `settings.py`.
            'name': f'{imgName}.{img.format}',
            'content': ContentFile(outputIO.getvalue()),
            'save': False,
        }



    def save(self, **kwargs):

        if not self.default:
            self.default.save(
                **self.handleResize(MediaSize.DEFAULT)
            )

        if not self.medium:
            self.medium.save(
                **self.handleResize(MediaSize.MEDIUM)
            )

        if not self.thumbnail:
            self.thumbnail.save(
                **self.handleResize(MediaSize.THUMBNAIL)
            )

        super().save(**kwargs)