【问题标题】:GAE: How to get the blob-image heightGAE:如何获得 blob 图像高度
【发布时间】:2011-06-15 08:54:12
【问题描述】:
Given 是 GAE 上的以下模型:
avatar = db.BlobProperty()
通过调用图像实例属性高度或宽度 (see documentation):
height = profile.avatar.height
抛出以下错误:
AttributeError: 'Blob' 对象没有属性 'height'
PIL 已安装。
【问题讨论】:
标签:
python
google-app-engine
blob
python-imaging-library
【解决方案1】:
如果图像存储在 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
【解决方案2】:
blob 不是图像,它是一个数据块。
要从您的 blob 中生成 Image,如果您的 blob 存储在 blobstore 中,则必须调用 Image(blob_key=your_blob_key);如果 blob 作为 blob 存储在数据存储区中,则必须调用 Image(image_data=your_image_data)。
【解决方案3】:
要在不应用转换的情况下获取图像大小,可以使用 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