ValueError: Fileobj 必须实现读取

Qaz*_*zal 5 file-upload amazon-s3 iplimage

我正在使用 PIL 库将 gif 图像转换为 jpg 并将它们上传到 s3。我收到此错误:

ValueError: Fileobj 必须实现读取

这是读取图像并转换为jpg的代码的一部分:

im = Image.open(url)
i = 0
mypalette = im.getpalette()
try:
    while 1:
            im.putpalette(mypalette)
            new_im = Image.new("RGBA", im.size)
            new_im.paste(im)
            key = 'img'+str(i)+'.jpg'
            in_mem_file = io.BytesIO()
            new_im.save(in_mem_file, "JPEG")
            s3.upload_fileobj(in_mem_file.getvalue(), bucket, key)
            i += 1
            im.seek(im.tell() + 1)
except EOFError:
            pass
Run Code Online (Sandbox Code Playgroud)

我使用 io.BytesIO 来读取字节,但是我仍然遇到相同的错误。如果我从 in_mem_file 中删除 getvalue 空图像保存在存储桶中。

小智 5

将图像重新保存到 BytesIO 缓冲区

with BytesIO() as in_mem_file:
    image.save(in_mem_file, format=image.format)
    in_mem_file.seek(0)
    s3client.upload_fileobj(in_mem_file, BUCKET, path)
Run Code Online (Sandbox Code Playgroud)

  • 谢谢!最后一行应该是 `s3client.upload_fileobj(in_mem_file, BUCKET, path)` (2认同)