How to validate image dimensions?

788 views
Skip to first unread message

Léon Dignòn

unread,
Aug 21, 2009, 4:40:56 AM8/21/09
to Django users
Hello,

in my ModelForm I try to allow only images (for avatar) smaller than
64*64 pixels. I've done this by overriding clean_avatar(). But how can
I check the dimensions? The instance is an InMemoryUploadedFile which
has no width or height. Any help regarding this?

class UserProfileForm(ModelForm):
class Meta:
model = UserProfile
exclude = ('user',) # User will be filled in by the view.

def clean_avatar(self):
img = self.cleaned_data['avatar']

if img.size > 10000: # working fine!
raise forms.ValidationError("Filesize too big. Max. 10k")
if img.width > 64: # 'InMemoryUploadedFile' object has no
attribute 'width'
raise forms.ValidationError("Not more than 64*64 pixels.")
return img

TiNo

unread,
Aug 21, 2009, 4:50:32 AM8/21/09
to django...@googlegroups.com
You can do this with PIL:

import Image
image = Image.open(img) 
if image.size[0] > 64: #image.size is a 2-tuple (width, height)
  ...

Or you could resize it down to 64 px if it is bigger.

TiNo

Alex Gaynor

unread,
Aug 21, 2009, 12:10:53 PM8/21/09
to django...@googlegroups.com
If you call django.core.files.images. get_image_dimensions on the file
you'll get back a width, height dimension tuple.

Alex

--
"I disapprove of what you say, but I will defend to the death your
right to say it." -- Voltaire
"The people's good is the highest law." -- Cicero
"Code can always be simpler than you think, but never as simple as you
want" -- Me

Léon Dignòn

unread,
Aug 22, 2009, 5:14:03 AM8/22/09
to Django users
Thank you!
I will youse TiNo's solutions. The resize feature is huge!

On Aug 21, 6:10 pm, Alex Gaynor <alex.gay...@gmail.com> wrote:
> On Fri, Aug 21, 2009 at 3:50 AM, TiNo<tin...@gmail.com> wrote:
> want" -- Me- Hide quoted text -
>
> - Show quoted text -
Reply all
Reply to author
Forward
0 new messages