将图片转换为Base64编码,解析base64格式从新生成图片

/**
* 将图片转换成Base64编码
* @param imgFile 待处理图片 /Applications/开发常用文件/mmexport1555768366578.jpg
* @return
*/
public static String getImgStr(String imgFile){
//将图片文件转化为字节数组字符串,并对其进行Base64编码处理
InputStream in = null;
byte[] data = null;
//读取图片字节数组
try {
in = new FileInputStream(imgFile);
data = new byte[in.available()];
in.read(data);
in.close();
}
catch (IOException e) {
e.printStackTrace();
}
return new String(Base64.encodeBase64(data));
}

/**
* 对字节数组字符串进行Base64解码并生成图片
* @param imgStr 图片数据
* @param imgFilePath 保存图片全路径地址
* @return
*/
public static boolean generateImage(String imgStr,String imgFilePath){
if (imgStr == null) { //图像数据为空
return false;
}
try {
//Base64解码
byte[] b = Base64.decodeBase64(imgStr);
for(int i=0;i<b.length;++i) {
if(b[i]<0) {//调整异常数据
b[i]+=256;
}
}
//生成jpeg图片
OutputStream out = new FileOutputStream(imgFilePath);
out.write(b);
out.flush();
out.close();
return true;
} catch (Exception e) {
return false;
}
}

/**
* * MultipartFile转成InputStream
*  将图片转换成Base64编码

  * 

 * MultipartFile  file;
* byte [] byteArr=file.getBytes();
* InputStream inputStream = new ByteArrayInputStream(byteArr);
* @param uploadFiles
* @return
*/
public static String imgTransformationBase64(@RequestParam("uploadFiles") MultipartFile uploadFiles){
InputStream in = null;
byte[] data = null;
//读取图片字节数组
try {
byte [] byteArr = uploadFiles.getBytes();
in = new ByteArrayInputStream(byteArr);
data = new byte[in.available()];
in.read(data);
in.close();
}
catch (IOException e) {
e.printStackTrace();
} catch (Exception e1) {
e1.getMessage();
e1.printStackTrace();
}
System.err.println(new String(Base64.encodeBase64(data)).length());
System.err.println(new String(Base64.encodeBase64(data)));
return new String(Base64.encodeBase64(data));
}

posted on 2020-12-13 14:00  UnmatchedSelf  阅读(1007)  评论(2编辑  收藏  举报

导航