Skip to content

Instantly share code, notes, and snippets.

@RussellLuo
Last active August 29, 2015 14:21
Show Gist options
  • Save RussellLuo/4fbb8f6a4fa4b5d2cffe to your computer and use it in GitHub Desktop.
Save RussellLuo/4fbb8f6a4fa4b5d2cffe to your computer and use it in GitHub Desktop.
Limit the format and size (width and height) of the uploaded image in Django.
from cStringIO import StringIO
from PIL import Image
from django.http import HttpResponse
ALLOWED_FORMAT = (
'JPEG',
'PNG',
)
ALLOWED_SIZE = (
(80, 60),
(100, 85),
)
def upload(request):
"""The handler of the upload request."""
if request.method == 'POST' and request.FILES:
f = request.FILES['file']
data = f.read() # save file data for reuse
fimage = StringIO(data)
if check_image(StringIO(data)):
return allow(fimage)
else:
return deny(fimage)
def check_image(fimage):
"""Check the format and size (width and height) of `fimage`."""
image = Image.open(fimage)
return image.format in ALLOWED_FORMAT and image.size in ALLOWED_SIZE
def allow(fimage):
"""The action when check successful."""
return HttpResponse('true')
def deny(fimage):
"""The action when check failed."""
return HttpResponse('false')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment