python中的内存缩略图生成
我将上传的图像存储在gridfs(mongodb)中。因此,映像数据永远不会保存在正常的文件系统上。这通过使用以下代码来实现:python中的内存缩略图生成,python,django,python-imaging-library,gridfs,Python,Django,Python Imaging Library,Gridfs,我将上传的图像存储在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:
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、枕头、sorl缩略图或任何最适合我的东西
我想知道是否有一种方法可以在不将文件临时保存到文件系统的情况下生成缩略图。这样会更干净,开销更少。是否有内存中的缩略图生成器
更新
保存缩略图的解决方案:
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)
然后通过提供文件。您可以将其保存到对象而不是文件(如果可能,请使用cStringIO
模块):
或者,如果您喜欢上下文管理器:
import contextlib
from StringIO import StringIO
with contextlib.closing(StringIO()) as handle:
thing.save(handle)
contents = handle.getvalue()
您可以将文件对象替换为
StringIO
,这样您就可以使用几乎所有的图像库进行替换。谢谢!用一个例子来回答这个问题,我会接受的:)生成缩略图有问题,我更新了我的question@Alp:ImageOps.fit
似乎不需要文件对象。你不应该在那里传递图像对象吗?你是对的,我再次更新了我的问题,因为我遇到了一个新问题
import contextlib
from StringIO import StringIO
with contextlib.closing(StringIO()) as handle:
thing.save(handle)
contents = handle.getvalue()