18

サイズ変更された画像を 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
4

3 に答える 3

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())
于 2011-07-14T13:03:08.363 に答える
0

私の推測でKey.set_contents_from_filenameは、単一の文字列引数が必要ですが、im2によって返される他のオブジェクト型であるを渡していますImage.resize。サイズ変更された画像を名前ファイルとしてファイルシステムに書き出してから、そのファイル名をに渡す必要があると思いますk.set_contents_from_filenameKeyそれ以外の場合は、メモリ内の構造 (StringIO または何らかのオブジェクト インスタンス) から画像の内容を取得できるクラス内の別のメソッドを見つけます。

于 2011-07-13T22:44:21.160 に答える