圖片由於檔案比較大,常用的圖片如多採用讀取資料庫或者檔案的方式會加大系統的負載。採用緩衝儲存的方法可以增加效率。
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;@Servicepublic class ImageRedisImpl implements ImageRedis {@Resourceprivate RedisTemplate<String, String> redisTemplateS; //redis的配置參考前面的文章,@Overridepublic 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("圖片:輸入參數有問題。");}}@Overridepublic 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; }}