在Django中将UploadedFile转换为PIL图像

时间:2021-04-16 00:25:19

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.

现在,我可以读取该文件,并将其保存到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},
        )

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.

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

Is there a way to do something like

有没有办法做类似的事情

img = Image.open(filedata)

3 个解决方案

#1


3  

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))

#2


1  

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

#3


1  

The code bellow creates the image from the request, as you want:

下面的代码根据您的需要从请求创建图像:

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


3  

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))

#2


1  

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

#3


1  

The code bellow creates the image from the request, as you want:

下面的代码根据您的需要从请求创建图像:

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)