package com.hx.util;
|
|
import sun.misc.BASE64Decoder;
|
import sun.misc.BASE64Encoder;
|
|
import java.io.*;
|
|
/**
|
* 图片和base64字符转换工具
|
* @USER: fhx
|
* @DATE: 2023/4/6
|
**/
|
public class ImageBase64Util {
|
|
/**
|
* base64字符串转化成图片
|
* @param base64
|
* @param fileName
|
* @param filePath
|
* @return
|
* @throws Exception
|
*/
|
public static File base64ToFile(String base64, String fileName, String filePath) throws Exception {
|
if(base64.contains("data:image")){
|
base64 = base64.substring(base64.indexOf(",")+1);
|
}
|
base64 = base64.replace("\r\n", "");
|
//创建文件目录
|
File file = File.createTempFile(base64, fileName, new File(filePath));
|
BufferedOutputStream bos = null;
|
FileOutputStream fos = null;
|
try {
|
BASE64Decoder decoder = new BASE64Decoder();
|
byte[] bytes = decoder.decodeBuffer(base64);
|
fos = new FileOutputStream(file);
|
bos = new BufferedOutputStream(fos);
|
bos.write(bytes);
|
}finally {
|
if (bos != null) {
|
try {
|
bos.close();
|
} catch (IOException e) {
|
e.printStackTrace();
|
}
|
}
|
if (fos != null) {
|
try {
|
fos.close();
|
} catch (IOException e) {
|
e.printStackTrace();
|
}
|
}
|
}
|
return file;
|
}
|
|
/**
|
* 图片转化成base64字符串
|
* @param imgFile
|
* @return
|
*/
|
public static String GetImageStr(File 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();
|
}
|
//对字节数组Base64编码
|
BASE64Encoder encoder = new BASE64Encoder();
|
return encoder.encode(data);//返回Base64编码过的字节数组字符串
|
}
|
|
}
|