Upload resized image to S3

Viewed 16767

I'm trying to upload resized image to 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)

but I get an error:

 in set_contents_from_filename
    fp = open(filename, 'rb')
TypeError: coercing to Unicode: need string or buffer, instance found
3 Answers
print ("loading object", input_bucket, input_key)
response = s3client.get_object(Bucket=input_bucket, Key=input_key)
print("s3 get object response", response)

body = response['Body']

image = Image.open(body)

print ("generating thumbnail", output_width, output_height)

thumbnail = resizeimage.resize_thumbnail(
    image, [output_width, output_height])
body.close()

print ("saving thumbnail", output_format)

with io.BytesIO() as output:
    thumbnail.save(output, output_format)

    print ("uploading thumbnail", output_bucket, output_key)
    output.seek(0)
    s3client.put_object(Bucket=output_bucket, Key=output_key,
                        Body=output, ContentType=output_content_type)
Related