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
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)
My guess is that Key.set_contents_from_filename
expects a single string argument, but you are passing in im2
, which is some other object type as returned by Image.resize
. I think you will need to write your resized image out to the filesystem as a name file and then pass that file name to k.set_contents_from_filename
. Otherwise find another method in the Key
class that can get the image contents from an in-memory construct (StringIO or some object instance).
You need to convert your output image into a set of bytes before you can upload to s3. You can either write the image to a file then upload the file, or you can use a cStringIO object to avoid writing to disk as I've done here:
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())