简体   繁体   English

如何使用 python / PIL 将图像存储到 redis

[英]how to store an image into redis using python / PIL

I'm using python and the Image module(PIL) to process images.我正在使用 python 和图像模块 (PIL) 来处理图像。

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.我想将图像 object 的原始位 stream 存储到 redis,以便其他人可以使用 nginx 和 httpredis 直接从 redis 读取图像。

so, my question is how to get the raw bits of an Image object and store it into redis.所以,我的问题是如何获取图像 object 的原始位并将其存储到 redis 中。

Using PIL 1.1.7, redis-2.7.2 pip module, and redis-2.4.10 I was able to get this working: 使用PIL 1.1.7,redis-2.7.2 pip模块和redis-2.4.10我能够正常工作:

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()

I found that Image.tostring was not reliable, so this method uses StringIO to make a string appear to be a file. 我发现Image.tostring不可靠,所以这个方法使用StringIO使字符串看起来像一个文件。 The format=im.format is needed because StringIO doesn't have an "extension". format=im.format是必需的,因为StringIO没有“扩展名”。 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. 并验证我得到了一张图片。

import redis
r =  redis.StrictRedis()
img = open("/path/to/img.jpeg","rb").read()
r.set("bild1",img)

works here too! 在这里工作!

For python 3 use io.Bytes or io.StringIO对于 python 3 使用 io.Bytes 或 io.StringIO

def image_to_byte_array(image: Image) -> bytes:
  # BytesIO is a fake file stored in memory
  imgByteArr = io.BytesIO()
  # image.
# r.set("0": my_bytes)save expects a file as a argument, passing a bytes io ins
  image.save(imgByteArr, format='PNG')
  # Turn the BytesIO object back into a bytes object
  imgByteArr = imgByteArr.getvalue()
  return imgByteArr

bytes = image_to_byte_array(im)
...
r.set("0", bytes)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM