方法 : 傳入文件路徑和base64位的編碼
/**
* base64轉(zhuǎn)為圖片
* @param path
* 文件路徑:到文件夾即可,代碼里會(huì)在文件夾里生成對應(yīng)的jpg文件
* @param base64
* @return
*/
public static String base64ToJpg(String path,String base64){
// 判斷文件路徑是否存在
File filePath = new File(path);
if (!filePath.exists()){
filePath.mkdirs();
}
// 創(chuàng)建文件
String jpgFile = path + "\\" + UUID.randomUUID() + ".jpg";
File file = new File(jpgFile);
boolean jpgFileExist = false;
try {
jpgFileExist = file.createNewFile();
log.info("jpg文件創(chuàng)建成功");
} catch (IOException e) {
log.info("jpg文件創(chuàng)建失敗");
e.printStackTrace();
}
if (jpgFileExist){
// 解密
Base64.Decoder decoder = Base64.getDecoder();
// 去掉base64前綴 data:image/jpeg;base64,
base64 = base64.substring(base64.indexOf(",", 1) + 1, base64.length());
byte[] b = decoder.decode(base64);
// 處理數(shù)據(jù)
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {
b[i] += 256;
}
}
// 保存圖片
try {
FileOutputStream out = new FileOutputStream(jpgFile);
out.write(b);
out.flush();
out.close();
// 寫入成功返回文件路徑
return jpgFile;
} catch (FileNotFoundException e) {
log.info("文件未找到");
e.printStackTrace();
} catch (IOException e) {
log.info("寫入失敗");
e.printStackTrace();
}
}
return "文件不存在";
}
main方法文章來源:http://www.zghlxwxcb.cn/news/detail-542143.html
public static void main(String[] args) {
Map<String, Object> imageCode = getImageCode();
log.info(imageCode.get("imageCodeKey").toString());
log.info(imageCode.get("imageCodeBase64").toString());
String base64 = imageCode.get("imageCodeBase64").toString();
String filePath = "C:\\Users\\Asus\\Desktop\\temp";
String res = base64ToJpg(filePath, base64);
log.info(res);
}
結(jié)果
文章來源地址http://www.zghlxwxcb.cn/news/detail-542143.html
到了這里,關(guān)于java base64轉(zhuǎn)圖片的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!