將圖片轉換為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));
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM