在Django中将UploadedFile转换为PIL图像

Mik*_*ein 5 python django python-imaging-library

在保存之前,我正在尝试检查图像的尺寸.我不需要改变它,只要确保它符合我的极限.

现在,我可以读取该文件,并将其保存到AWS而没有任何问题.

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},
        )
Run Code Online (Sandbox Code Playgroud)

我需要在中间放一步,以确保文件具有正确的尺寸/宽度尺寸.我的文件不是来自使用ImageField的表单,而且我见过的所有解决方案都使用它.

有没有办法做类似的事情

img = Image.open(filedata)
Run Code Online (Sandbox Code Playgroud)

小智 1

我以前做过这个,但我找不到我的旧片段......所以我们在这里胡思乱想

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()
Run Code Online (Sandbox Code Playgroud)