工具类中的图片解密的代码
/*** base64字符串转图片* @param imgStr 图片的base64* @param path 将要生成的地址* @return*/
public static String generateImage(String imgStr, String path) {//如果图像数据为空 if (imgStr == null) {return null;}BASE64Decoder decoder = new BASE64Decoder();try {//解密byte[] b = decoder.decodeBuffer(imgStr);//处理数据for (int i = 0; i < b.length; ++i) {if (b[i] < 0) {b[i] += 256;}}//图片名称String fileName= CommonUtil.paserDateToStr(new Date(), "yyyyMMddHHmmss")+".jpg";File image = new File(path+fileName);if (!image.exists()) {image.getParentFile().mkdir();}OutputStream out = new FileOutputStream(path+fileName);out.write(b);out.flush();out.close();//返回图片地址+名称,方便存入数据库中return (path+fileName);} catch (IOException e) {e.printStackTrace();return null;}
}
application.properties文件中静态资源配置(我的项目是Springboot)
##
web.img-path=D:/image/
web.thumbnail-file=thumbnail
spring.mvc.static-path-pattern=/**
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,file:${web.img-path}
Controller控制层引入配置文件中静态资源路径
@Value("${web.img-path}")
private String imgPath;// 调用工具类中图片解码方法,传入需要解码成图片的字符串以及图片保存地址,进行解码保存
String picaddress = CommonUtil.generateImage("imgStr",imgPath));
然后就完成了,因为我所传的值不是Base64图片加密后的字符串,所以图片打不开
这里是图片加密的代码
/*** 图片转base64字符串* @param imgFile 图片路径* @return*/public static String imageToBase64Str(String imgFile) {InputStream inputStream = null;byte[] data = null;try {inputStream = new FileInputStream(imgFile);data = new byte[inputStream.available()];inputStream.read(data);inputStream.close();} catch (IOException e) {e.printStackTrace();}// 加密BASE64Encoder encoder = new BASE64Encoder();return encoder.encode(data);}
我暂时还没用到图片加密,所以并不知道这段代码是否绝对正确
PS:如果你的Eclipse中无法直接使用Base64Encoder:
1.右键项目——》Build Path ——》Configure Build Path
2.选择Libraries,点击JRE System Library,选择 Access rules,之前没有定义的话,就会显示No rules defined
3.选中Access rules,点击Edit ——》Add,然后点击Ok
4.在Resolution下拉列表框中选择Accessible,Rule Pattern 选择**,依次点击ok
问题解决。此时你的Eclipse中就能使用Base64Encoder啦