Convert UploadedFile to PIL file in Django

I am trying to check the image size before saving it. I do not need to change it, just make sure it meets my limitations.

Now I can read the file and save it to AWS without any problems.

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 take a middle step so that the file has the correct size and width dimensions. My file does not come from a form that uses ImageField, and all the solutions I saw use it.

Is there a way to do something like

img = Image.open(filedata)
+5
source share
3 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))
+3
source

I have done this before, but I can’t find my old fragment ... so we are leaving our heads>

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()
+1

, :

from PIL import ImageFile
def image_upload(request):
    for f in request.FILES.values():
        p = ImageFile.Parser()
        while 1:
            s = f.read(1024)
            if not s:
                break
            p.feed(s)
        im = p.close()
        im.save("/tmp/" + f.name)
+1

All Articles