2017-09-13 137 views
0

我想从网上获取图像并将其上传到Amazon s3。虽然这样做,我想检查图像尺寸。 我在Python 3以下代码:将PIL图像对象上传到Amazon s3 python

from PIL import Image 
import requests 

# Get response 
response = requests.get(url, stream= True) 

# Open image 
im = Image.open(response.raw) 

# Get size 
size = im.size 

# Upload image to s3 
S3.Client.upload_fileobj(
    im, # This is what i am trying to upload 
    AWS_BUCKET_NAME, 
    key, 
    ExtraArgs={ 
     'ACL': 'public-read' 
    } 
) 

的问题是,PIL图像对象不支持读取。当我尝试上传PIL图像对象im时出现以下错误。

ValueError: Fileobj must implement read 

它工作时,我只是尝试上传'response.raw',但我需要得到的图像尺寸。如何将PIL图像对象更改为文件类对象?有没有更容易的方式来获得尺寸,同时仍然能够上传图像到S3?

所以问题是,在获取图像的尺寸后,如何将图像上传到s3?

回答

3

而不是调用read(),以获得该文件的内容回来,你的文件“保存”到任何一个真正的文件对象或像内存对象的文件。然后调用getValue()。

下面是一个示例函数,您可以将文件内容传递给它,打印出高度和宽度,然后以AWS客户端put_object函数将接受的格式返回文件数据作为Body参数。

from PIL import Image 
import io 

def modify_image(image, format): 
    pil_image = Image.open(image) 

    # Prints out (1280, 960) 
    print(pil_image.size) 

    in_mem_file = io.BytesIO() 

    # format here would be something like "JPEG". See below link for more info. 
    pil_image.save(in_mem_file, format=format) 
    return in_mem_file.getvalue() 

也有不同的宽度和高度属性在这里:http://pillow.readthedocs.io/en/3.4.x/reference/Image.html#attributes

查看更多有关文件格式,这里http://pillow.readthedocs.io/en/3.4.x/handbook/image-file-formats.html

注:示例使用Python 3.6.1

0

您应该使用

response = requests.get(url, stream= True) 
f = io.BytesIO(response.content) 
image = Image.open(f) 
+0

这并不能改变什么。图像打开正常。当我想将图像上传到s3时,会出现问题。 – john

+0

您是否尝试将'f'加载到aws?用'f'代替'im' – AndMar

+0

是的,我试过了。首先,'response'没有一个名为'read'的属性,我假设你的意思是'response.raw.read()'。当我尝试这样做时,我上传了一个空的file_obj,因为当用Image.open()打开时,f已被清空。 – john