python - 将 jpg、gif、png 等存储到 gae-datastore

标签 python image google-app-engine file-upload

我找到了一个 example关于如何在数据存储中存储 png:

  img = images.Image(img_data)
  # Basically, we just want to make sure it's a PNG
  # since we don't have a good way to determine image type
  # through the API, but the API throws an exception
  # if you don't do any transforms, so go ahead and use im_feeling_lucky.
  img.im_feeling_lucky()
  png_data = img.execute_transforms(images.PNG)

  img.resize(60, 100)
  thumbnail_data = img.execute_transforms(images.PNG)

  Picture(data=png_data,
          thumbnail_data=thumbnail_data).put()

这段代码让我很困惑,但它适用于 png。但是,我应该怎么做才能存储所有最常见的格式(jpg、gif、tiff 等)?

最佳答案

快速回答

您可以在模型中使用 db.BlobProperty() 存储任何文件类型的二进制数据。

如果您使用Image API 来操作图像数据,您只能输入.jpg.png.gif.bmp.tiff.ico 类型,并输出到 .jpg.png


存储图片

要简单地将图像存储在数据存储中,请在您的模型中使用 db.BlobProperty(),并让它存储图片的二进制数据。这就是数据在您链接到的示例代码中的存储方式(请参阅 Line 85)。

因为 db.BlobProperty 类型本身不是图片,而是可以存储任何二进制数据,所以需要一些纪律;没有简单的方法来以编程方式强制执行仅图片约束。幸运的是,这意味着您可以存储任何类型的数据,包括 .jpg.gif.tiff 等文件添加到 .png 格式,如示例中所示。

您可能希望像他们在示例中所做的那样,为模型创建一个新类,并存储文件所需的某些元数据(“名称”、“文件类型”等),以及图像的二进制数据。您可以在 Line 65 上看到这样的示例在您链接到的示例中。

要将图像存储在 BlobProperty 中,您需要使用 db.put() 来保存数据;这与任何类型都一样。请参阅从 Line 215 开始的代码在您链接到的示例代码中。


处理图像

如果你必须操作图像,你可以使用 Images API包裹。来自Overview of the Images API我们可以看到以下内容:

The service accepts image data in the JPEG, PNG, GIF (including animated GIF), BMP, TIFF and ICO formats.

It can return transformed images in the JPEG and PNG formats. If the input format and the output format are different, the service converts the input data to the output format before performing the transformation.

因此,即使您在技术上可以在数据存储中存储任何类型,但如果您使用此 API 来操作图像,则有效的输入和输出类型是有限的。

关于python - 将 jpg、gif、png 等存储到 gae-datastore,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5211780/

相关文章:

python 更改数字格式 ndarray 许多位

google-app-engine - 是否有 GWT 库与新的 AppEngine Channel API 接口(interface)

android - com.google.appengine.tools.cloudstorage 包不存在

javascript - 图像调整大小以适合屏幕

python - 如何测量图像中的颜色接近度/浓度? (首选Python解决方案)

python - 在 tkinter 中查看的枕头生成图像中的颜色与保存文件中的颜色不匹配

google-app-engine - 谷歌应用引擎 : Odd get_by_key_name behavior

python - Django 外键的模型字段未正确更新

python paho mqtt 客户端连接通过 ssl/tls 给出错误

Python:通过另一个函数中的参数对列表进行排序