djangoimagedjango-modelsimagefielddjango-imagekit

How to save the generated image from Django ImageKit to ImageField?


I generate the image using the code below:

source_file = open('/path/to/myimage.jpg', 'rb')
image_generator = Thumbnail(source=source_file)
result = image_generator.generate()

What is the proper method to save the generated "result" back to django ImageField? ie in a model The generated result seems to be a _io.BytesIO object. And it seems I cannot directly save it to ImageField.

Any help would be appreciated


Solution

  • Assuming you have a SampleModel as below,

    class SampleModel(models.Model):
        image = models.ImageField(null=True)
    


    then,ContentFile do the magic for you. Follow the snippet,

    from django.core.files.base import ContentFile
    
    source_file = open('/path/to/myimage.jpg', 'rb')
    image_generator = Thumbnail(source=source_file)
    result = image_generator.generate()
    # additional snippet
    django_file = ContentFile(result.getvalue())
    sample = SampleModel.objects.create()
    sample.image.save('sample_name.jpg', django_file)
    sample.save()