Redis storage Image [Base64/url/path]vs[object]

Source: Internet
Author: User


One, base64 picture codec


Basic process: Download a picture from the network, then Base64 encoding, and then base64 decoding, stored in the local e-packing directory.


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 {
* *
*Base 64 bit encoding of network pictures
*
* @param imageUrl
*The URL path of the picture, such as http: / /.... xx.jpg
* @return
* /
Public static string encodeimagetobase64 (URL imageurl) {/ / converts a picture file to a byte array string and encodes 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();
}
//Encoding byte array Base64
BASE64Encoder encoder = new BASE64Encoder();
Return encoder. Encode (OutputStream. Tobytearray()); / / returns the base64 encoded byte array string
}
* *
*Base 64 bit encoding of local pictures
*
* @param imageFile
*The URL path of the image, such as F: /.... xx.jpg
* @return
* /
Public static string encodeimagetobase64 (file imagefile) {/ / converts a picture file to a byte array string and encodes it with Base64
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();
}
//Encoding byte array Base64
BASE64Encoder encoder = new BASE64Encoder();
Return encoder. Encode (OutputStream. Tobytearray()); / / returns the base64 encoded byte array string
}
* *
*Decode the base64 bit encoded picture and save it to the specified directory
*
* @param base64
*Base64 encoded picture 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");
}
} 


The results of the Base64 encoding of the console output:



View E Packing directory:


Second, Redis objects object storage


When Redis stores object data, it is the object's serialization and deserialization operations.


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 {
* *
* serialization
*
* @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;
}
} 
 Packagepackage RedisObject;
import redis.clients.jedis.Jedis;
public class PersonRedisTest {
private static Jedis jedis = null;
* *
*Initializing the jedis object
*
* @throws Exception
* /
public PersonRedisTest() {
jedis = new Jedis("127.0.0.1", 6379);
}
* *
*Serialize the write object and write the person object to 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 get 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();
}
} 


Run the main function result:



To view data for Redis storage:


Three, Redis storage pictures


In the P22 (page 22nd) of the Redis Starter guide, there is a passage:
The string type is the most basic data type in Redis, and it can store any form of string, including binary data. You can use it to store a user's mailbox, a JSON object, or even a picture. ”
Redis is a data structure type of server, not simply key-value storage. The keys inside the Redis are binary security (binary security means that data is secured during transmission, including encryption, etc.), so the contents of the keys should not contain spaces or line breaks. For example, "Hello World" and "Hello world\n" are wrong.
So how do you store images in Redis? Plainly, the picture is a set of binary data, direct storage of binary data is certainly not possible, to achieve Redis storage binary data, then you have to implement the conversion beforehand.
The process of Base64 codec and Redis storage objects has been written in one or two. Then we can do this. Store images in Redis:


    1. Convert a picture into a string
      (1) We can store images in Redis base64 encoding or decoding, in KV format, K is the normal string, V for the image of the Base64 encoding, get (K) and then Base64 decoding can be;
      (2) We can also store the network URL of the image in Redis or the local path path, the implementation can be stored on the image itself to disk, and then in Redis with the network URL of the picture or the local path path to the value (V) stored.
    2. Convert images to object objects
      Store picture objects directly in Redis, using the Java serialization/deserialization mechanism for processing implementations.


Redis storage Image [Base64/url/path]vs[object]


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.