gpt4 book ai didi

python - 将调整大小的图像上传到 S3

转载 作者:IT老高 更新时间:2023-10-28 20:57:00 26 4
gpt4 key购买 nike

我正在尝试将调整大小的图像上传到 S3:

fp = urllib.urlopen('http:/example.com/test.png')
img = cStringIO.StringIO(fp.read())

im = Image.open(img)
im2 = im.resize((500, 100), Image.NEAREST)
AK = 'xx' # Access Key ID
SK = 'xx' # Secret Access Key

conn = S3Connection(AK,SK)
b = conn.get_bucket('example')
k = Key(b)
k.key = 'example.png'
k.set_contents_from_filename(im2)

但我得到一个错误:

 in set_contents_from_filename
fp = open(filename, 'rb')
TypeError: coercing to Unicode: need string or buffer, instance found

最佳答案

您需要将输出图像转换为一组字节,然后才能上传到 s3。您可以将图像写入文件然后上传文件,也可以使用 cStringIO 对象来避免写入磁盘,就像我在这里所做的那样:

import boto
import cStringIO
import urllib
import Image

#Retrieve our source image from a URL
fp = urllib.urlopen('http://example.com/test.png')

#Load the URL data into an image
img = cStringIO.StringIO(fp.read())
im = Image.open(img)

#Resize the image
im2 = im.resize((500, 100), Image.NEAREST)

#NOTE, we're saving the image into a cStringIO object to avoid writing to disk
out_im2 = cStringIO.StringIO()
#You MUST specify the file type because there is no file name to discern it from
im2.save(out_im2, 'PNG')

#Now we connect to our s3 bucket and upload from memory
#credentials stored in environment AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY
conn = boto.connect_s3()

#Connect to bucket and create key
b = conn.get_bucket('example')
k = b.new_key('example.png')

#Note we're setting contents from the in-memory string provided by cStringIO
k.set_contents_from_string(out_im2.getvalue())

关于python - 将调整大小的图像上传到 S3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6685500/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com