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

时间:2011-07-13 20:52:03

标签: python amazon-s3 python-imaging-library boto

我正在尝试将已调整大小的图片上传到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

3 个答案:

答案 0 :(得分:57)

您需要先将输出图像转换为一组字节,然后才能上传到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())

答案 1 :(得分:0)

我的猜测是Key.set_contents_from_filename需要单个字符串参数,但是您传入的是im2,这是Image.resize返回的其他一些对象类型。我认为您需要将已调整大小的图像作为名称文件写入文件系统,然后将该文件名传递给k.set_contents_from_filename。否则在Key类中找到另一个可以从内存构造(StringIO或某个对象实例)获取图像内容的方法。

答案 2 :(得分:0)

<java classpath="${classpath-translated}" classname="${classname}" dir="${work.dir}" jvm="${platform.java}" fork="true" failonerror="${java.failonerror}">
            <jvmarg value="-Dfile.encoding=${encoding}"/>
            <redirector inputencoding="${encoding}" outputencoding="${encoding}" errorencoding="${encoding}"/>
            <jvmarg line="${run.jvmargs}" />
            <arg line="${application.args}" />
            <syspropertyset>
                <propertyref prefix="run-sys-prop."/>
                <mapper from="run-sys-prop.*" to="*" type="glob"/>
            </syspropertyset>
        </java>