views:

499

answers:

2

I see a lot of people with Django apps that have image uploads are automatically resizing the images after they are uploaded. That is well and good for some cases, but I don't want to do this. Instead, I simply want to force the user to upload a file that is already the proper size.

I want to have an ImageField where I force the user to upload an image that is 100x200. If the image they upload is not exactly that size, I want the admin form to return as invalid. I would also like to be able to do the same thing for aspect ratios. I want to force the user to upload an image that is 16:9 and reject any upload that does not conform.

I already know how to get the width and height of the image, but I can't do that server-side until after the image is already uploaded, and the form is submitted successfully. How can I check this earlier, if possible?

+8  A: 

The right place to do this is during form validation.
A quick example (will edit/integrate with more info later):

from django.core.files.images import get_image_dimensions
class myForm(forms.ModelForm):
   class Meta:
       model = myModel
   def clean_picture(self):
       picture = self.cleaned_data.get("picture")
       if not picture:
           raise forms.ValidationError("No image!")
       else:
           w, h = get_image_dimensions(picture)
           if w != 100:
               raise forms.ValidationError("The image is %i pixel wide. It's supposed to be 100px" % w)
           if h != 200:
               raise forms.ValidationError("The image is %i pixel high. It's supposed to be 200px" % h)
       return picture
Agos
I was too slow, here's the related link:http://docs.djangoproject.com/en/dev/ref/forms/validation/#cleaning-a-specific-field-attribute
monkut
While this solution is cool for reference, the OP said he wants to check the dimensions of the image BEFORE form submission. So it has to be something client side. Or am I misreading his last paragraph?
celopes
I don't necessarily mean before form submission, as long as it's before the model is saved.
Apreche
Well, then I think you found your winner! :-)
celopes
A: 

This may be a dupe of/very similar to this question:

Using jQuery, Restricting File Size Before Uploading

I don't think there is a way to do it the way you want. Agos solution is the way to go...

Edit: One of the answers in the linked SO question talks about using flash to do it. So while it may be possible to do with some other technology, I don't think you can do it with straight javascript.

celopes
Another possible technology could be a Java applet. I've seen quite a number of uploaders tackle the matter that way. It's also useful in case you actually want to allow big/plenty of uploads.
Agos