Custom save method for images/avatars in Django - how to use - python

So, I'm trying to do a little bit of compression of images as well as some other operations. I had a few questions...I have the following save() method for my user class:
class User(AbstractBaseUser, PermissionsMixin):
...
avatar = models.ImageField(storage=SITE_UPLOAD_LOC, null=True, blank=True)
def save(self, *args, **kwargs):
if self.avatar:
img = Img.open(BytesIO(self.avatar.read()))
if img.mode != 'RGB':
img = img.convert('RGB')
new_width = 200
img.thumbnail((new_width, new_width * self.avatar.height / self.avatar.width), Img.ANTIALIAS)
output = BytesIO()
img.save(output, format='JPEG', quality=70)
output.seek(0)
self.avatar= InMemoryUploadedFile(file=output, field_name='ImageField', name="%s.jpg" % self.avatar.name.split('.')[0], content_type='image/jpeg', size=, charset=None)
super(User, self).save(*args, **kwargs)
I had two questions:
Best way for deleting the old avatar file on save, if a previous avatar exists
What do I pass into InMemoryUploadedFile for the size kwarg? Is this the size of the file? in what unit/(s)?

You need to get file size. Try this:
import os
size = os.fstat(output.fileno()).st_size
You can read this for how to get file size:
https://docs.python.org/3.0/library/stat.html
and for deleting old avtar. According to your code it is foreign key hence before saving you can check if avtar is already exists and so yoy can delete it.
Add this lines code after output.seek(0) this line:
if self.avtar:
self.avtar.delete()

What you want is the size in bytes.
You can get the byte size of a BytesIO object like this.
size = len(output.getvalue())

Related

Django Resize Image Before Saving

Goal: Upload a resized image (with same file name and aspect ratio) to AWS S3.
Problem: Currently upon saving, the original image is uploaded and not the resized one.
What have I tried?: I've tried multiple different ways to accomplish this but I run into various issues such as not the correct aspect ratio, poor image quality (when using django-resize) etc. The code below seems really close but I just can't seem to find where I am going wrong.
models.py
class Profile(BaseModel):
user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True)
image = models.ImageField(default='default.jpg', upload_to='profile_pics')
def save(self, commit=True, *args, **kwargs): #Edited
if commit:
img = Image.open(self.image)
if img.height > 300 or img.width > 300:
output_size = (300, 300)
img.thumbnail(output_size)
img.save(self.image.name, optimize=True, quality=100)
super().save()
Solution:
After a very long time I finally found the answer in this blog.
In the end I made a new function in the users/utils.py file:
from django.core.files import File
from pathlib import Path
from PIL import Image
from io import BytesIO
image_types = {
"jpg": "JPEG",
"jpeg": "JPEG",
"png": "PNG",
"gif": "GIF",
"tif": "TIFF",
"tiff": "TIFF",
}
def image_resize(image, width, height):
# Open the image using Pillow
img = Image.open(image)
# check if either the width or height is greater than the max
if img.width > width or img.height > height:
output_size = (width, height)
# Create a new resized “thumbnail” version of the image with Pillow
img.thumbnail(output_size)
# Find the file name of the image
img_filename = Path(image.file.name).name
# Spilt the filename on “.” to get the file extension only
img_suffix = Path(image.file.name).name.split(".")[-1]
# Use the file extension to determine the file type from the image_types dictionary
img_format = image_types[img_suffix]
# Save the resized image into the buffer, noting the correct file type
buffer = BytesIO()
img.save(buffer, format=img_format)
# Wrap the buffer in File object
file_object = File(buffer)
# Save the new resized file as usual, which will save to S3 using django-storages
image.save(img_filename, file_object)
and then overwrote the save() function in the models.py:
models.py
from users.utils import image_resize
class Profile(BaseModel):
#some other fields
image = models.ImageField(default='default.jpg', upload_to='profile_pics')
def save(self, commit=True, *args, **kwargs):
if commit:
image_resize(self.image, 250, 250)
super().save(*args, **kwargs)

How to validate of dimensions in default ImageField?

Have a following rule in the project: the image field is optional and a default image is an uninformed case for the user. Images are sent by the user in django and must have a dimension (width> = 900, height> = 400).
I am trying to validate the dimensions in admin.py, but it is giving problem when I try to register when it has default argument in imagefield.
Gives an image error not found even though it is in the directory. Without the validation function in admin.py it works normally.
models.py
class Event(models.Model):
banner = models.ImageField('banner', upload_to='events/banners', default='events/banners/banner_padrao_eventos.png', blank=True)
admin.py
class EventForm(forms.ModelForm):
class Meta:
model = Event
fields = '__all__'
def clean_banner(self):
banner = self.cleaned_data.get('banner')
if banner:
img = Image.open(banner)
width, height = img.size
max_width = 900
max_height = 400
if width < max_width or height < max_height:
raise forms.ValidationError(
'Image is incorrectly sized:% s x% s pixels. Please insert an image with% s x% s pixels.'
% (width, height, max_width, max_height))
if len(banner) > (3 * 1024 * 1024):
raise forms.ValidationError('Very large image file (maximum of 3MB).')
name_img, ext = banner.name.split('.')
if not (ext.lower() in ['png', 'jpg', 'jpeg']):
raise forms.ValidationError('Please use the image in JPG, JPEG or PNG format.')
else:
raise forms.ValidationError('The loaded image could not be read.')
return banner
How can I make the default image to be considered in the validation?
The file uploaded is Django InMemoryUploadedFile file it's not saved in your server yet, open() needs that the file exists physically or as string bytes. To do that you need the package PIL.Image and io.BytesIO
from io import BytesIO as StringIO
from PIL import Image
img = Image.open(StringIO(banner.read()))
So now, img.size is a tuple containing your width and height
width, height = img.size

RuntimeError - maximum recursion depth exceeded

i create a function that create a thumbnail when uploading an image. I can upload the image and create the thumbnail out of it. But the result that i got is the thumbnail was created more than one until and i got the error that i've mention aboved.
def save(self, *args, **kwargs):
"""
Make and save the thumbnail for the photo here.
"""
super(AerialFoto, self).save(*args, **kwargs)
if not self.make_thumbnail():
raise Exception('Could not create thumbnail - is the file type valid?')
def make_thumbnail(self):
"""
Create and save the thumbnail for the photo (simple resize with PIL).
"""
THUMB_SIZE = (100,100)
fh = storage.open(self.image.name, 'rb')
try:
image = Image.open(fh)
except:
return False
image.thumbnail(THUMB_SIZE, Image.ANTIALIAS)
fh.close()
# Path to save to, name, and extension
thumb_name, thumb_extension = os.path.splitext(self.image.name)
thumb_extension = thumb_extension.lower()
thumb_filename = thumb_name + 'thumbs' + thumb_extension
if thumb_extension in ['.jpg', '.jpeg']:
FTYPE = 'JPEG'
elif thumb_extension == '.gif':
FTYPE = 'GIF'
elif thumb_extension == '.png':
FTYPE = 'PNG'
else:
return False # Unrecognized file type
# Save thumbnail to in-memory file as StringIO
temp_thumb = StringIO()
image.save(temp_thumb, FTYPE)
temp_thumb.seek(0)
# Load a ContentFile into the thumbnail field so it gets saved
self.thumbnail.save(thumb_filename, ContentFile(temp_thumb.read()), save=True)
temp_thumb.close()
Traceback
http://dpaste.com/1ZG838R
save() calls make_thumbnail(), which calls self.thumbnail.save(...), which ends up calling save() again, and around and around it goes.
You have to break the loop somewhere. My suggestion: make_thumbnail() shouldn't save anything, it should just create the thumbnail and store it on say self._thumbnail_data= temp_thumb.read();.
Then in the save() function, only call self.make_thumbnail() if self._thumbnail_data isn't already set. Once you know self._thumbnail_data exists then you can do self.thumbnail.save(thumb_filename, self._thumbnail_data, save=True).
This happens because save calls make_thumbnail and make_thumbnail calls save again, you need to break the loop when the make_thumbnail has already saved the thumbnail.
Check in the save args if a thumbnail content is provided and if not call make_thumbnail

Django - Get I/O error on changing object attribute

In my views.py file, I am trying to add 1 to a BigIntegerField named visited_counter.
views.py :
def view_page(request,id_page):
page = get_object_or_404(Page,title=id_page)
page.visited_counter= page.visited_counter +1
page.save()
return render(request,'app/page.html',locals())
models.py :
class Page(models.Model):
title = models.CharField(max_length=30)
visited_counter= models.BigIntegerField()
landscape= models.BooleanField()
thumbnail = models.ImageField(storage=OverwriteStorage(),upload_to=thumbnail_path)
backgroundpicture =models.ImageField(storage=OverwriteStorage(),upload_to=background_path)
def save(self, *args, **kwargs):
if self.backgroundpicture.width >= self.backgroundpicture.height:
self.landscape=True
else:
self.landscape=False
if self.backgroundpicture:
from PIL import Image
import glob, os
from cStringIO import StringIO
from django.core.files.uploadedfile import SimpleUploadedFile
image = Image.open(self.backgroundpicture) ####LINE ERROR####
try:
# thumbnail
THUMBNAIL_SIZE = (160, 160) # dimensions
# Convert to RGB if necessary
if image.mode not in ('L', 'RGB'): image = image.convert('RGB')
# create a thumbnail + use antialiasing for a smoother thumbnail
image.thumbnail(THUMBNAIL_SIZE, Image.ANTIALIAS)
# fetch image into memory
temp_handle = StringIO()
image.save(temp_handle, 'JPEG')
temp_handle.seek(0)
# save it
file_name, file_ext = os.path.splitext(self.backgroundpicture.name.rpartition('/')[-1])
suf = SimpleUploadedFile(file_name + file_ext, temp_handle.read(), content_type='JPEG')
self.thumbnail.save(file_name + '.jpg', suf, save=False)
except ImportError:
pass
super(Page, self).save(*args, **kwargs)
When I create a 'Page object', I have no problem.... The save function is doing her job very well, but when I want to access to the object via the view_page function. I get a I/O operation on closed file error on that line: image = Image.open(self.backgroundpicture).
I didn't find any other Q/A related to this case, so I am stuck...
The trick is to add an if condition in your save method and check if it is necessary to read the whole code in the save function.
For this you add a function named, has_changed
def has_changed(instance, field, manager='objects'):
"""Returns true if a field has changed in a model
May be used in a model.save() method.
"""
if not instance.pk:
return True
manager = getattr(instance.__class__, manager)
old = getattr(manager.get(pk=instance.pk), field)
return not getattr(instance, field) == old
And you use it in the model definition like this:
if has_changed(self, 'backgroundpicture'):
if self.backgroundpicture.width >= self.backgroundpicture.height:
self.landscape=True
...

Django Image upload and resize

I have a standard Django form with an image field. When the image is uploaded, I would like to make sure that the image is no larger than 300px by 300px. Here is my code:
def post(request):
if request.method == 'POST':
instance = Product(posted_by=request.user)
form = ProductModelForm(request.POST or None, request.FILES or None)
if form.is_valid():
new_product = form.save(commit=False)
if 'image' in request.FILES:
img = Image.open(form.cleaned_data['image'])
img.thumbnail((300, 300), Image.ANTIALIAS)
# this doesnt save the contents here...
img.save(new_product.image)
# ..because this prints the original width (2830px in my case)
print new_product.image.width
The problem I am facing is, it is not clear to me how I get the Image type converted to the type that ImageField type.
From the documentation on ImageField's save method:
Note that the content argument should be an instance of django.core.files.File, not Python's built-in file object.
This means you would need to convert the PIL.Image (img) to a Python file object, and then convert the Python object to a django.core.files.File object. Something like this (I have not tested this code) might work:
img.thumbnail((300, 300), Image.ANTIALIAS)
# Convert PIL.Image to a string, and then to a Django file
# object. We use ContentFile instead of File because the
# former can operate on strings.
from django.core.files.base import ContentFile
djangofile = ContentFile(img.tostring())
new_product.image.save(filename, djangofile)
There you go, just change a little bit to suit your need:
class PhotoField(forms.FileField, object):
def __init__(self, *args, **kwargs):
super(PhotoField, self).__init__(*args, **kwargs)
self.help_text = "Images over 500kb will be resized to keep under 500kb limit, which may result in some loss of quality"
def validate(self,image):
if not str(image).split('.')[-1].lower() in ["jpg","jpeg","png","gif"]:
raise ValidationError("File format not supported, please try again and upload a JPG/PNG/GIF file")
def to_python(self, image):
try:
limit = 500000
num_of_tries = 10
img = Image.open(image.file)
width, height = img.size
ratio = float(width) / float(height)
upload_dir = settings.FILE_UPLOAD_TEMP_DIR if settings.FILE_UPLOAD_TEMP_DIR else '/tmp'
tmp_file = open(os.path.join(upload_dir, str(uuid.uuid1())), "w")
tmp_file.write(image.file.read())
tmp_file.close()
while os.path.getsize(tmp_file.name) > limit:
num_of_tries -= 1
width = 900 if num_of_tries == 0 else width - 100
height = int(width / ratio)
img.thumbnail((width, height), Image.ANTIALIAS)
img.save(tmp_file.name, img.format)
image.file = open(tmp_file.name)
if num_of_tries == 0:
break
except:
pass
return image
Source: http://james.lin.net.nz/2012/11/19/django-snippet-reduce-image-size-during-upload/
How about using standard image field https://github.com/humanfromearth/django-stdimage
Here is an app that can take care of that: django-smartfields
from django.db import models
from smartfields import fields
from smartfields.dependencies import FileDependency
from smartfields.processors import ImageProcessor
class Product(models.Model):
image = fields.ImageField(dependencies=[
FileDependency(processor=ImageProcessor(
scale={'max_width': 300, 'max_height': 300}))
])
Try my solution here: https://stackoverflow.com/a/25222000/3731039
Highlight
Using Pillow for image processing (two packages required: libjpeg-dev, zlib1g-dev)
Using Model and ImageField as storage
Using HTTP POST or PUT with multipart/form
No need to save the file to disk manually.
Create multiple resolutions and stores their dimensions.
You can use my library django-sizedimagefield for this, it has no extra dependency and is very simple to use.

Categories

Resources