【发布时间】:2013-06-28 01:23:30
【问题描述】:
我将上传的图像存储在 gridfs (mongodb) 中。因此,图像数据永远不会保存在普通文件系统上。这通过使用以下代码来工作:
import pymongo
import gridfs
conn = pymongo.Connection()
db = conn.my_gridfs_db
fs = gridfs.GridFS(db)
...
with fs.new_file(
filename = 'my-filename-1.png',
) as fp:
fp.write(image_data_as_string)
我还想存储该图像的缩略图。我不在乎使用哪个库,PIL、Pillow、sorl-thumbnail 或任何最适合我的库。
我想知道是否有一种方法可以在不将文件临时保存在文件系统中的情况下生成缩略图。那会更干净,开销也更少。是否有内存缩略图生成器?
更新
我保存缩略图的解决方案:
from PIL import Image, ImageOps
content = cStringIO.StringIO()
content(icon)
image = Image.open(content)
temp_content = cStringIO.StringIO()
thumb = ImageOps.fit(image, (width, height), Image.ANTIALIAS)
thumb.save(temp_content, format='png')
temp_content.seek(0)
gridfs_image_data = temp_content.getvalue()
with fs.new_file(
content_type = mimetypes.guess_type(filename)[0],
filename = filename,
size = size,
width = width,
height = height,
) as fp:
fp.write(gridfs_image_data)
然后通过nginx-gridfs 提供文件。
【问题讨论】:
-
您可以用
StringIO替换文件对象,因此您几乎可以使用任何图像库来实现。 -
谢谢!用一个例子来回答这个问题,我会接受它:)
标签: python django python-imaging-library gridfs