【问题标题】:In-memory thumbnail generation in pythonpython中的内存缩略图生成
【发布时间】: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、sor​​l-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


【解决方案1】:

您可以将其保存到StringIO 对象而不是文件(如果可能,请使用cStringIO 模块):

from StringIO import StringIO

fake_file = StringIO()
thing.save(fake_file)  # Acts like a file handle
contents = fake_file.getvalue()
fake_file.close()

或者如果你喜欢上下文管理器:

import contextlib
from StringIO import StringIO

with contextlib.closing(StringIO()) as handle:
    thing.save(handle)
    contents = handle.getvalue()

【讨论】:

  • 生成缩略图时遇到问题,我更新了我的问题
  • @Alp: ImageOps.fit 似乎不需要文件对象。你不应该在那里传递一个图像对象吗?
  • 你是对的,我再次更新了我的问题,因为我遇到了一个新问题
猜你喜欢
  • 1970-01-01
  • 2012-04-22
  • 2018-10-19
  • 2013-11-23
  • 1970-01-01
  • 2015-08-24
  • 2010-12-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多