How do I store images correctly in Redis or Valkey?
Asked Answered
M

2

10

Decided to store images in Redis, how to do it correctly? Now I do this:

$redis->set('image_path', 'here is the base64 image code');

I'm not sure this is normal.

Marked answered 8/12, 2020 at 18:45 Comment(4)
I mean, that'll probably work, but why? Base64ing the image will add 33% file size, and RAM is a lot more expensive than disk storage.Unipolar
@ceejayoz, I'm parsing one site with a lot of images. So I want to store images somewhere so that I don't have to make constant requests to them. Are you thinking of using file storage?Marked
Yes, a file-based cache would likely be much better in a variety of ways.Unipolar
@ceejayoz, Thank you very much for your help. Make out a response so that I can accept it and your reputation will improve.Marked
D
18

It is perfectly ok to store images in Valkey/Redis. Keys and values are both binary-safe

Strings are binary safe, this means that a string can contain any kind of data, for instance a JPEG image or a serialized Ruby object.

A String value can be at max 512 Megabytes in length.

You can store the image in binary instead of base64 and it will be more efficient:

  • In RAM memory usage on your server
  • In Network usage
  • In compute (CPU) usage assuming you are passing the images in binary to the final client

You can do

$client->set('profile_picture', file_get_contents("profile.png"));

See Storing Binary Data in Redis

Delicatessen answered 8/12, 2020 at 21:28 Comment(1)
What's the best for img storage? In the cloud and retrieve via cdn or in Redis?Potpie
G
7

Here is my simple example of storing image file into Redis Database and retrieve them as well

from PIL import Image
import redis
from io import BytesIO


output = BytesIO()
im = Image.open("/home/user/im.jpg")
im.save(output, format=im.format)

r = redis.StrictRedis(host='localhost', port= 6379, db =0)
r.set('imgdata', output.getvalue())
output.close()
r.save  #redis-cli --raw get 'imgdata' >test.jpg
Godwin answered 21/8, 2021 at 5:43 Comment(1)
OP is using phpMavis

© 2022 - 2024 — McMap. All rights reserved.