Redis stores images in [base64/url/path] vs [object]
I. base64 image Codec
Basic Process: download an image from the network, encode it with base64, decode it with base64, and save it to the root directory of the local edisk.
Import java. awt. image. bufferedImage; import java. io. byteArrayOutputStream; import java. io. file; import java. io. fileOutputStream; import java. io. IOException; import java.net. malformedURLException; import java.net. URL; import javax. imageio. imageIO; import sun. misc. BASE64Decoder; import sun. misc. BASE64Encoder; @ SuppressWarnings ("restriction") public class Base64ImageUtils {/*** encode the url path of the image by base64** @ param imageUrl *, as shown in figure http://.....xx.jpg * @ Return */public static String encodeImgageToBase64 (URL imageUrl) {// convert the image file to a byte array String and encode it with Base64. ByteArrayOutputStream outputStream = null; try {BufferedImage bufferedImage = ImageIO. read (imageUrl); outputStream = new ByteArrayOutputStream (); ImageIO. write (bufferedImage, "jpg", outputStream);} catch (MalformedURLException e1) {e1.printStackTrace ();} catch (IOException e) {e. printStackTrace ();} // encode the byte array BASE64Encoder encoder = new BASE64Encoder (); return encoder. encode (outputStream. toByteArray (); // returns the Base64 encoded byte array string}/*** encode the local image in Base64 bits ** @ param imageFile * the url path of the image, for example, F:/....xx.jpg * @ return */public static String encodeImgageToBase64 (File imageFile) {// convert the image File to a byte array String, and Base64 encoding ByteArrayOutputStream outputStream = null; try {BufferedImage bufferedImage = ImageIO. read (imageFile); outputStream = new ByteArrayOutputStream (); ImageIO. write (bufferedImage, "jpg", outputStream);} catch (MalformedURLException e1) {e1.printStackTrace ();} catch (IOException e) {e. printStackTrace ();} // encode the byte array BASE64Encoder encoder = new BASE64Encoder (); return encoder. encode (outputStream. toByteArray (); // returns the Base64 encoded byte array string}/*** decodes the Base64 encoded image, and save it to the specified directory ** @ param base64 * base64 encoded image information * @ return */public static void decodeBase64ToImage (String base64, String path, String imgName) {BASE64Decoder decoder = new BASE64Decoder (); try {FileOutputStream write = new FileOutputStream (new File (path + imgName); byte [] decoderBytes = decoder. decodeBuffer (base64); write. write (decoderBytes); write. close ();} catch (IOException e) {e. printStackTrace () ;}} public static void main (String [] args) {URL url = null; try {url = new URL (" http://www.faceplusplus.com.cn/wp-content/themes/faceplusplus/assets/img/demo/9.jpg ");} Catch (MalformedURLException e) {e. printStackTrace ();} String encoderStr = Base64ImageUtils. encodeImgageToBase64 (url); System. out. println (encoderStr); Base64ImageUtils. decodeBase64ToImage (encoderStr, "E:/", "football.jpg ");}}
Base64-encoded result output by the console:
View the root directory of the edisk:
Ii. Redis object Storage
When Redis stores object data, it needs to serialize and deserialize the object.
package RedisObject;import java.io.Serializable;public class Person implements Serializable { private static final long serialVersionUID = 1L; private int id; private String name; public Person() { } public Person(int id, String name) { super(); this.id = id; this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; }}
Package RedisObject; import java. io. byteArrayInputStream; import java. io. byteArrayOutputStream; import java. io. objectInputStream; import java. io. objectOutputStream; public class SerializeUtil {/*** serialize ** @ param object * @ return */public static byte [] serialize (Object object) {ObjectOutputStream oos = null; byteArrayOutputStream baos = null; try {baos = new ByteArrayOutputStream (); oos = new ObjectOutputStream (baos); oos. writeObject (object); byte [] bytes = baos. toByteArray (); return bytes;} catch (Exception e) {} return null ;} /*** deserialization ** @ param bytes * @ return */public static Object unserialize (byte [] bytes) {ByteArrayInputStream bais = null; try {bais = new ByteArrayInputStream (bytes); ObjectInputStream ois = new ObjectInputStream (bais); return ois. readObject () ;}catch (Exception e) {} return null ;}}
Package RedisObject; import redis. clients. jedis. jedis; public class PersonRedisTest {private static Jedis jedis = null;/*** initialize Jedis object ** @ throws Exception */public PersonRedisTest () {jedis = new Jedis ("127.0.0.1", 6379);}/*** serialize the write object and write the Person object into Redis **/public void setObject () {jedis. set ("person: 100 ". getBytes (), SerializeUtil. serialize (new Person (100, "zhangsan"); jedis. set ("person: 101 ". getBytes (), SerializeUtil. serialize (new Person (101, "bruce");}/*** deserialize the object and use Jedis to obtain the object **/public void getObject () {byte [] data100 = jedis. get ("person: 100 "). getBytes (); Person person100 = (Person) SerializeUtil. unserialize (data100); System. out. println (String. format ("person: 100-> id = % s, name = % s", person100.getId (), person100.getName (); byte [] data101 = jedis. get ("person: 101 "). getBytes (); Person person101 = (Person) SerializeUtil. unserialize (data101); System. out. println (String. format ("person: 101-> id = % s, name = % s", person101.getId (), person101.getName ();} public static void main (String [] args) {PersonRedisTest rt = new PersonRedisTest (); rt. setObject (); rt. getObject ();}}
Result of running main function:
View the data stored in Redis:
Iii. Redis Image Storage
In P22 (page 1) of The Redis Getting Started Guide, there is a saying:
"The string type is the most basic data type in Redis. It can store any form of string, including binary data. You can use it to store users' mailboxes, JSON objects, and even images ."
Redis is a data structure server, not simply a key-value storage. Keys in Redis are binary secure (Binary security guarantees data security during data transmission, including encryption). Therefore, the key content should not contain spaces or line breaks. For example, "hello world" and "hello world \ n" are incorrect.
So how to store images in Redis? To put it bluntly, the image is a set of binary data, and direct storage of binary data is definitely not good. To achieve Redis to store binary data, you must implement conversion in advance.
I/O 2 has written the base64 encoding and decoding process of the image and the redis storage object process. Then we can store images in Redis like this:
Convert an image to a String
(1) We can store the base64 encoding or decoding of images in Redis. In the KV format, K is a common string, V is the base64 encoding of the image, and get (K) and then base64 decoding;
(2) We can also store the image's network url or local path in Redis. The specific implementation can make the image itself stored in the disk, in Redis, the network url of the image or the local path is stored as the value (V) value.
Convert an image to an object
Stores image objects directly in Redis and uses Java serialization/deserialization mechanisms for processing.