Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting an UploadedFile to PIL image in Django

I'm trying to check an image's dimension, before saving it. I don't need to change it, just make sure it fits my limits.

Right now, I can read the file, and save it to AWS without a problem.

output['pic file'] = request.POST['picture_file']
conn = myproject.S3.AWSAuthConnection(aws_key_id, aws_key)
filedata = request.FILES['picture'].read()
content_type = 'image/png'
conn.put(
        bucket_name,
        request.POST['picture_file'],
        myproject.S3.S3Object(filedata),
        {'x-amz-acl': 'public-read', 'Content-Type': content_type},
        )

I need to put a step in the middle, that makes sure the file has the right size / width dimensions. My file isn't coming from a form that uses ImageField, and all the solutions I've seen use that.

Is there a way to do something like

img = Image.open(filedata)
like image 373
Mike Stein Avatar asked Sep 23 '11 16:09

Mike Stein


2 Answers

image = Image.open(file)
#To get the image size, in pixels.    
(width,height) = image.size() 
#check for dimensions width and height and resize
image = image.resize((width_new,height_new))
like image 73
tukan Avatar answered Sep 23 '22 14:09

tukan


I've done this before but I can't find my old snippet... so here we go off the top of my head

picture = request.FILES.get['picture']
img = Image.open(picture)
#check sizes .... probably using img.size and then resize

#resave if necessary
imgstr = StringIO()
img.save(imgstr, 'PNG') 
imgstr.reset()

filedata = imgstr.read()
like image 25
toad013 Avatar answered Sep 21 '22 14:09

toad013