本文介绍了上传调整图像到S3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图调整后的图像上传到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'#访问密钥ID
SK ='XX'#访问密钥
康恩= S3Connection(AK,SK)
B = conn.get_bucket(示例)
K =键(B)
k.key ='example.png
k.set_contents_from_filename(IM2)
但我得到一个错误:
在set_contents_from_filename
计划生育=打开(文件名,RB)
类型错误:强迫到统一code:需要字符串或缓冲区,比如发现
解决方案
您需要将您的输出图像转换为一组字节,然后才能上传到S3。您可以写入图像文件,然后上传文件,也可以使用cStringIO对象,以避免写入磁盘,因为我在这里所做的:
进口博托
cStringIO导入
进口的urllib
进口图片
从URL #Retrieve我们的源图像
FP =了urllib.urlopen('http://example.com/test.png)
#Load URL数据成图像
IMG = cStringIO.StringIO(fp.read())
IM = Image.open(IMG)
#Resize图像
IM2 = im.resize((500,100),Image.NEAREST)
#NOTE,我们保存图像到cStringIO对象,以避免写入磁盘
out_im2 = cStringIO.StringIO()
#你必须指定文件类型,因为那里是从辨别它没有文件名
im2.save(out_im2,PNG)
#Now我们连接到我们的S3存储和上传从内存
存储环境AWS_ACCESS_KEY_ID和AWS_SECRET_ACCESS_KEY #credentials
康恩= boto.connect_s3()
#Connect来桶和创建密钥
B = conn.get_bucket(示例)
K = b.new_key('example.png)
#Note我们从cStringIO提供的内存串设置内容
k.set_contents_from_string(out_im2.getvalue())
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
解决方案
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())
这篇关于上传调整图像到S3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!