package org.jeecg.common.util;
import org.apache.commons.codec.binary.Base64;
import sun.misc.BASE64Decoder;
import java.io.*;
public class ImgBase64 {
/**
* 將圖片轉換成Base64編碼
* @param imgFile 待處理圖片
* @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 Base64.encodeBase64String(data);
}
/**
* 對字節數組字符串進行Base64解碼並生成圖片
* @param imgStr 圖片數據
* @param imgFilePath 保存圖片全路徑地址
* @return
*/
public static boolean generateImage(String imgStr, String imgFilePath) {
//
if (imgStr == null) // 圖像數據為空
return false;
BASE64Decoder decoder = new BASE64Decoder();
try {
// Base64解碼
byte[] b = decoder.decodeBuffer(imgStr);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {// 調整異常數據
b[i] += 256;
}
}
// 生成jpg圖片
OutputStream out = new FileOutputStream(imgFilePath);
out.write(b);
out.flush();
out.close();
return true;
} catch (Exception e) {
return false;
}
}
}
調用:
String url= "D:\\1.jpg";// 待處理的圖片
String imgbese = getImgStr(url);
String img_path="data:image/jpeg;base64,"+imgbese ;
String url= "D:\\1.jpg";// 新生成的圖片
generateImage(imgbese, url);
jar包:
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.13</version>
</dependency>
