Reputation: 5578
I'm trying to resize a file while the image is uploaded, but I'm have some issue trying to save it into my model's ImageField.
Here is my models.py :
try:
from PIL import Image, ImageOps
except ImportError:
import Image
import ImageOps
class IMGResize(models.Model):
image = models.ImageField(upload_to='images', blank=True)
def save(self, *args, **kwargs):
if self.image:
img = Image.open(self.image) #<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=980x490 at 0x59E4B38>
imageresize = img.resize((200, 200), Image.ANTIALIAS) #<PIL.Image.Image image mode=RGB size=200x200 at 0x4D5F630>
imageresize.save('newname.jpg', 'JPEG', quality=75) #not being saved here to my models
super(IMGResize, self).save(*args, **kwargs)
How can I resolve this so I can save the resized image into my model ?
Upvotes: 0
Views: 1878
Reputation: 5578
I found the answer on this post by madzohana, which works without any issue.
from PIL import Image
from io import BytesIO
from django.core.files.base import ContentFile
def save(self, *args, **kwargs):
img = Image.open(self.image)
resized = img.resize((200, 200), Image.ANTIALIAS)
new_image_io = BytesIO()
if img.format == 'JPEG' :
resized .save(new_image_io, format='JPEG')
elif img.format == 'PNG' :
resized.save(new_image_io, format='PNG')
temp_name = self.image.name
self.image.delete(save=False)
self.image.save(
temp_name,
content=ContentFile(new_image_io.getvalue()),
save=False
)
super(IMGResize, self).save(*args, **kwargs)
Upvotes: 2
Reputation: 6379
I believe this will do the trick (edited for PIL Image objects:
from django.core.files.base import ContentFile
import StringIO
....
class IMGResize(models.Model):
image = models.ImageField(upload_to='images', blank=True)
def safe(self, *args, **kwargs):
if self.image:
img = Image.open(self.image)
imageresize = img.resize((200, 200), Image.ANTIALIAS)
image_formatted = Image.open(StringIO(imageresize.content))
image_io = StringIO()
image_formatted.save(image_io, format='JPEG')
self.image.save(self.image.name, ContentFile(image_io.getvalue(), True)
super(IMGResize, self).save(*args, **kwargs)
Upvotes: 1