Created
January 9, 2018 05:49
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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