GAE:如何获取blob图像高度
这里有一个关于GAE(谷歌应用引擎)的模型:
avatar = db.BlobProperty()
当你尝试调用图片实例的高度或宽度属性时(可以查看文档),使用的是:
height = profile.avatar.height
但是会出现以下错误:
AttributeError: 'Blob'对象没有'height'这个属性
PIL库已经安装好了。
3 个回答
0
如果想要获取图片的大小而不进行任何处理,可以通过一个叫做 BlobKey
的东西从一个叫做 blobstore 的地方获取图片数据,然后通过 BlobInfo
来得到这些数据的大小。
from google.appengine.api import blobstore
from google.appengine.api import images
# ...
image_data = blobstore.fetch_data(blob_key, 0, blob_info.size)
image = images.Image(image_data=image_data)
# image.width and image.height is accessible
5
一个blob并不是图片,它只是一些数据的集合。
要把你的blob变成一个Image
,你需要调用 Image(blob_key=your_blob_key)
,如果你的blob存储在blobstore里;或者使用 Image(image_data=your_image_data)
,如果它是作为blob存储在数据存储中。
13
如果图片存储在BlobProperty里,那么这些数据就保存在数据存储中。如果profile
是你的实体(也就是你要处理的数据),那么你可以这样获取图片的高度:
from google.appengine.api import images
height = images.Image(image_data=profile.avatar).height
如果图片是在blobstore里(也就是数据存储中的blobstore.BlobReferenceProperty),那么你有两种方法来获取它的大小。比较复杂的方法是获取blob的读取器,然后用这个读取器去读取exif信息来得到图片的尺寸。不过,还有一种更简单的方法:
如果avatar = db.BlobReferenceProperty()
,而profile
是你的实体,那么你可以这样做:
from google.appengine.api import images
img = images.Image(blob_key=str(profile.avatar.key()))
# we must execute a transform to access the width/height
img.im_feeling_lucky() # do a transform, otherwise GAE complains.
# set quality to 1 so the result will fit in 1MB if the image is huge
img.execute_transforms(output_encoding=images.JPEG,quality=1)
# now you can access img.height and img.width