如何使用python/PIL将图像存储到Redis中 [英] how to store an image into redis using python / PIL

查看:329
本文介绍了如何使用python/PIL将图像存储到Redis中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用python和图像模块(PIL)处理图像.

I'm using python and the Image module(PIL) to process images.

我想将图像对象的原始位流存储到redis,以便其他人可以使用nginx& httpredis.

I want to store the raw bits stream of the image object to redis so that others can directly read the images from redis using nginx & httpredis.

所以,我的问题是如何获取Image对象的原始位并将其存储到Redis中.

so, my question is how to get the raw bits of an Image object and store it into redis.

推荐答案

使用PIL 1.1.7,redis-2.7.2 pip模块和redis-2.4.10,我可以使它工作:

Using PIL 1.1.7, redis-2.7.2 pip module, and redis-2.4.10 I was able to get this working:

import Image
import redis
import StringIO

output = StringIO.StringIO()
im = Image.open("/home/cwgem/Pictures/portrait.png")
im.save(output, format=im.format)

r = redis.StrictRedis(host='localhost')
r.set('imagedata', output.getvalue())
output.close()

我发现Image.tostring不可靠,因此此方法使用StringIO使字符串看起来像是文件.需要format=im.format是因为StringIO没有扩展名".然后,我通过执行以下操作测试了图像数据是否已保存:

I found that Image.tostring was not reliable, so this method uses StringIO to make a string appear to be a file. The format=im.format is needed because StringIO doesn't have an "extension". I then tested the image data was saved okay by doing:

redis-cli --raw get 'imagedata' >test.png

并确认我得到了一张图片.

and verifying I got back an image.

这篇关于如何使用python/PIL将图像存储到Redis中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆