【问题标题】:AttributeError: read in PythonAttributeError:在 Python 中读取
【发布时间】:2014-10-26 13:36:25
【问题描述】:

我正在尝试获取图像,然后将其转换为 Python 可以理解的对象,然后上传。

这是我尝试过的:

# Read the image using .count to get binary
image_binary = requests.get(
    "http://danealva143.files.wordpress.com/2014/03/2012-08-girls-920-26.jpg").content


string_buffer = io.BytesIO()
string_buffer.write(image_binary)
string_buffer.seek(0)

files = {}
files['image'] = Image.open(string_buffer)
payload = {}

results = requests.patch(url="http://127.0.0.1:8000/api/profile/94/", data=payload, files=files)

我收到此错误:

  File "/Users/user/Documents/workspace/test/django-env/lib/python2.7/site-packages/PIL/Image.py", line 605, in __getattr__
    raise AttributeError(name)
AttributeError: read

为什么?

【问题讨论】:

    标签: python python-2.7 python-imaging-library python-requests


    【解决方案1】:

    您不能发布PIL.Image 对象; requests 需要一个文件对象。

    如果您不更改图像,则将数据加载到Image 对象中也没有任何意义。只需发送image_binary 数据即可:

    files = {'image': image_binary}
    results = requests.patch(url="http://127.0.0.1:8000/api/profile/94/", data=payload, files=files)
    

    您可能希望包含图像二进制文件的 mime 类型:

    image_resp = requests.get(
        "http://danealva143.files.wordpress.com/2014/03/2012-08-girls-920-26.jpg")
    files = {
        'image': (image_resp.url.rpartition('/')[-1], image_resp.content, image_resp.headers['Content-Type'])
    }
    

    如果您真的想操作图像,您首先必须将图像保存回文件对象:

    img = Image.open(string_buffer)
    # do stuff with `img`
    
    output = io.BytesIO()
    img.save(output, format='JPEG')  # or another format
    output.seek(0)
    
    files = {
        'image': ('somefilename.jpg', output, 'image/jpeg'),
    }
    

    Image.save() method 采用任意文件对象进行写入,但由于在这种情况下没有文件名可从中获取格式,因此您必须手动指定要写入的图像格式。从supported image formats 中选择。

    【讨论】:

    • 只是在这里做实验,但如果我想改变图像怎么办。我需要将其转回二进制即保存吗?
    • @Sputnik:添加了有关如何将 PIL 图像保存回 BytesIO 内存文件对象的信息。
    • 谢谢,帮了大忙:)
    猜你喜欢
    • 1970-01-01
    • 2017-06-17
    • 2011-09-26
    • 2021-06-03
    • 1970-01-01
    • 2020-09-04
    • 1970-01-01
    • 1970-01-01
    • 2019-06-12
    相关资源
    最近更新 更多