[Fixed]-Save image created via PIL to django model

19👍

I solved the issue with the following code:

       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()

I found the answer here How do you convert a PIL `Image` to a Django `File`?. Works flawlessly!!!

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)

Leave a comment