您的位置:首页 > 数据库 > Redis

redis 在spring boot工程中的应用(四) 图片的读取与缓存 byte string

2016-03-16 21:06 911 查看
图片由于文件比较大,常用的图片如多采用读取数据库或者文件的方式会加大系统的负载。采用缓存保存的方法可以增加效率。
http://stackoverflow.com/questions/13215024/weird-redis-key-with-spring-data-jedis 这里已经提供了图片的读取方法和类型转换方法,修改一下即可。

本文采用的是,将工程下的文件读入到redis缓存缓存数据库中。

读取文件和编码图片为字符串

public static String encodeToString(BufferedImage image, String type) {  //将<span style="font-family: Arial, Helvetica, sans-serif;">BufferedImage 转化为string,type是文件类型:jpg,png等</span>
String imageString = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();

try {
ImageIO.write(image, type, bos);
byte[] imageBytes = bos.toByteArray();

BASE64Encoder encoder = new BASE64Encoder();
imageString = encoder.encode(imageBytes);

bos.close();
} catch (IOException e) {
e.printStackTrace();
}
return imageString;
}
/*
* 读取图片
*/
public static String readImage(String fileName,String type){  //传入图片名和类型,读取文件并返回string
//<span style="font-family: Arial, Helvetica, sans-serif;">System.getProperty("user.dir") 是获取当前工程的根目录,target\\classes下是resource的目录,</span>
File file2 = new File(System.getProperty("user.dir")+"\\target\\classes\\static\\image\\"+fileName);
try {
BufferedImage img = ImageIO.read(file2);
BufferedImage newImg;
String imagestr;
imagestr = encodeToString(img, type);
return imagestr;
}
catch (FileNotFoundException ex1) {
ex1.printStackTrace();
}
catch (IOException ex1) {
ex1.printStackTrace();
}
return null;
}


图片在redis中保存于获取

package cn.edu.tju.redis;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
@Service
public class ImageRedisImpl implements ImageRedis {
@Resource
private RedisTemplate<String, String> redisTemplateS;  //redis的配置参考前面的文章,

@Override
public void save(String img, String name) {
if(name != null && img != null && img.length() > 0 && name.length() > 0){ //设置键值保存在redis中
String key = "photo."+name;
String value="";
value = new String(img);
redisTemplateS.opsForValue().set(key, value);
}
else {
System.out.println("图片:输入参数有问题!");
}
}

@Override
public byte[] get(String name) {
if(name != null){
String key = "photo."+name;  //通过传入文件名,返回图片的byte数组
String value = redisTemplateS.opsForValue().get(key);
byte[] x = decodeToImage(value);
return x;
}
return null;
}

public static byte[] decodeToImage(String imageString) {//解码

BufferedImage image = null;
byte[] imageByte = new byte[]{};
try {
BASE64Decoder decoder = new BASE64Decoder();
imageByte = decoder.decodeBuffer(imageString);
return imageByte;
//	         ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
//	         image = ImageIO.read(bis);
//	         bis.close();
} catch (Exception e) {
e.printStackTrace();
}
return imageByte;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息