Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload resized image to S3

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
like image 749
Rafał Kot Avatar asked Jul 13 '11 20:07

Rafał Kot


People also ask

Does S3 optimize images?

You can attach your AWS S3 bucket to ImageKit and start delivering optimized images in just a few minutes.

Does S3 have object size limits?

Individual Amazon S3 objects can range in size from a minimum of 0 bytes to a maximum of 5 TB. The largest object that can be uploaded in a single PUT is 5 GB. For objects larger than 100 MB, customers should consider using the Multipart Upload capability.

Can Amazon S3 store images?

You can upload any file type—images, backups, data, movies, etc. —into an S3 bucket. The maximum size of a file that you can upload by using the Amazon S3 console is 160 GB. To upload a file larger than 160 GB, use the AWS CLI, AWS SDK, or Amazon S3 REST API.

How do I upload images to Amazon S3?

To upload a photo to an album in the Amazon S3 bucket, the application's addPhoto function uses a file picker element in the web page to identify a file to upload. It then forms a key for the photo to upload from the current album name and the file name.


1 Answers

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())
like image 156
secretmike Avatar answered Oct 22 '22 06:10

secretmike