how to store an image into redis using python / PIL
Asked Answered
R

3

7

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

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.

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

Revolving answered 5/3, 2013 at 13:30 Comment(0)
J
21

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

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.

Jubbulpore answered 5/3, 2013 at 14:30 Comment(2)
how do you then read the image saved in python?Geophagy
import StringIO doesn't work anymore. The approach at https://mcmap.net/q/1048473/-how-do-i-store-images-correctly-in-redis-or-valkey works for me.Invincible
D
3
import redis
r =  redis.StrictRedis()
img = open("/path/to/img.jpeg","rb").read()
r.set("bild1",img)

works here too!

Dispassionate answered 17/10, 2014 at 13:50 Comment(0)
G
0

For python 3 use io.Bytes or 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)
Geophagy answered 6/1, 2023 at 19:16 Comment(1)
make sure that r = redis.Redis(decode_responses=False) or else it will fail by trying to decode the image after a getGeophagy

© 2022 - 2024 — McMap. All rights reserved.