将图像保存为字节并上传到boto3返回内容-MD5不匹配

use*_*691 15 amazon-s3 python-imaging-library python-3.x pillow boto3

我正在尝试从s3中提取图像,量化它/操纵它,然后将其存储回s3而不将任何内容保存到磁盘(完全在内存中).我曾经做过一次,但是在返回代码并再次尝试它之后就没用了.代码如下:

import boto3
import io
from PIL import Image

client = boto3.client('s3',aws_access_key_id='',
        aws_secret_access_key='')
cur_image = client.get_object(Bucket='mybucket',Key='2016-03-19 19.15.40.jpg')['Body'].read()

loaded_image = Image.open(io.BytesIO(cur_image))
quantized_image = loaded_image.quantize(colors=50)
saved_quantized_image = io.BytesIO()
quantized_image.save(saved_quantized_image,'PNG')
client.put_object(ACL='public-read',Body=saved_quantized_image,Key='testimage.png',Bucket='mybucket')
Run Code Online (Sandbox Code Playgroud)

我收到的错误是:

botocore.exceptions.ClientError: An error occurred (BadDigest) when calling the PutObject operation: The Content-MD5 you specified did not match what we received.
Run Code Online (Sandbox Code Playgroud)

如果我只是拉一个图像然后把它放回去而不操纵它,它工作正常.我不太确定这里发生了什么.

Nat*_*ord 35

我有同样的问题,解决方案是寻找保存的内存文件的开头:

out_img = BytesIO()
image.save(out_img, img_type)
out_img.seek(0)  # Without this line it fails
self.bucket.put_object(Bucket=self.bucket_name,
                       Key=key,
                       Body=out_img)
Run Code Online (Sandbox Code Playgroud)

  • 因为 `save` 函数使用指针来遍历文件。当它到达末尾时,它不会将指针重置为开头,因此任何未来的操作都从文件末尾开始。 (4认同)

Dmi*_*117 7

在将文件发送到S3之前,可能需要保存并重新加载该文件.文件指针搜索也需要为0.

我的问题是在读完文件的前几个字节后发送文件.干净地打开文件就可以了.