Skip to content

Instantly share code, notes, and snippets.

@uuz2333
Created January 9, 2018 05:49
Show Gist options
  • Select an option

  • Save uuz2333/d1eef4902458015d421a91ba45de9e71 to your computer and use it in GitHub Desktop.

Select an option

Save uuz2333/d1eef4902458015d421a91ba45de9e71 to your computer and use it in GitHub Desktop.
Resize or Modify an image before saving, copy from https://djangosnippets.org/snippets/10597/ , a back up
rom django.db import models
from PIL import Image
from io import BytesIO
from django.core.files.uploadedfile import InMemoryUploadedFile
import sys
# Create your models here.
class Modify(models.Model):
img = models.ImageField()
def save(self):
#Opening the uploaded image
im = Image.open(self.img)
output = BytesIO()
#Resize/modify the image
m.resize( (100,100) )
#after modifications, save it to the output
im.save(output, format='JPEG', quality=100)
output.seek(0)
#change the imagefield value to be the newley modifed image value
self.img = InMemoryUploadedFile(output,'ImageField', "%s.jpg" %self.img.name.split('.')[0], 'image/jpeg', sys.getsizeof(output), None)
super(Modify,self).save()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment