我正在构建一个Webapp,该Webapp接收上传的图像,将其存储在Amazon S3上,然后将URL存储在SQLite数据库中。不幸的是,EXIF标签会导致通过智能手机拍摄的图像看上去旋转(因为它们是带有EXIF方向标签的横向图像)。
当前,我的环境从POST数据中获取文件,将其保存到我的静态文件文件夹中,使用PIL旋转图像(如果需要),推送到S3,最后删除本地副本。以下是其中的一些代码:
from PIL import Image
import boto
from boto.s3.connection import S3Connection
from boto.s3.key import Key
def fix_orientation(filename):
img = Image.open(filename)
if hasattr(img, '_getexif'):
exifdata = img._getexif()
try:
orientation = exifdata.get(274)
except:
# There was no EXIF Orientation Data
orientation = 1
else:
orientation = 1
if orientation is 1: # Horizontal (normal)
pass
elif orientation is 2: # Mirrored horizontal
img = img.transpose(Image.FLIP_LEFT_RIGHT)
elif orientation is 3: # Rotated 180
img = img.rotate(180)
elif orientation is 4: # Mirrored vertical
img = img.rotate(180).transpose(Image.FLIP_LEFT_RIGHT)
elif orientation is 5: # Mirrored horizontal then rotated 90 CCW
img = img.rotate(-90).transpose(Image.FLIP_LEFT_RIGHT)
elif orientation is 6: # Rotated 90 CCW
img = img.rotate(-90)
elif orientation is 7: # Mirrored horizontal then rotated 90 CW
img = img.rotate(90).transpose(Image.FLIP_LEFT_RIGHT)
elif orientation is 8: # Rotated 90 CW
img = img.rotate(90)
#save the result and overwrite the originally uploaded image
img.save(filename)
def push_to_s3(**kwargs):
try:
conn = S3Connection(app.config["S3_KEY"], app.config["S3_SECRET"])
buckets = [bucket.name for bucket in conn.get_all_buckets()]
bucket = conn.get_bucket(app.config["S3_BUCKET"])
k = Key(bucket)
k.key = app.config["S3_UPLOAD_DIR"] + kwargs.get("filename")
k.set_contents_from_filename(kwargs.get("photo"))
k.make_public()
return k
except Exception, e:
abort(500)
这是处理POST数据
# Retrieving Form POST Data
fi = request.files.get("file")
#print "Storing and Rotating File (if needed)"
f = photos.save(fi)
path = photos.path(f)
fix_orientation(path)
#print "Uploading to S3"
img = push_to_s3(photo=path, filename=filename)
#print "Deleting Local Version"
os.remove(path)
上面的解决方案可以在Heroku的服务器上运行,但似乎只是解决方案的完美结合。有没有更清洁的方式来做我正在做的事情。也就是说,拿一个上传的文件,从内存中旋转它,然后推送到S3?
我还使用Flask-Uploads处理上传图像的存储。
对于什么是值得的,枕头支持许多其他输入不是文件名-其中包括bytearray
,buffer
,和file-like object
。第三个很可能是您要寻找的东西,因为从其中装载的任何东西request.files
都只是一个FileStorage
类似文件的对象。这将加载和转换代码简化为:
def fix_orientation(file_like_object):
img = Image.open(filename)
# ... snip ...
data = BytesIO()
img.save(data)
return data
由于我们将无需使用文件系统就可以非常方便地传递数据,因此我们也可以改用boto.s3.key.Key
的set_contents_from_file
方法代替set_contents_from_filename
:
def push_to_s3(photo, filename):
# ... snip ...
k.set_contents_from_file(photo, rewind=True)
# ... etc. ...
这样可以简化实现:
# Retrieving Form POST Data
fi = request.files.get("file")
# print "Rotating File (if needed)"
fi = fix_orientation(fi)
# print "Uploading to S3"
push_to_s3(photo=fi, filename=filename)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句