直播平台制作,base64图片字符串和file之间互相转换

直播平台制作,base64图片字符串和file之间互相转换

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
 
import java.io.*;
 
public class Base64Img {
 
//图片转化成base64字符串
 
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编码过的字节数组字符串
 
}
 
 
//base64字符串转化成图片
public static File base64ToFile(String base64, String fileName) throws Exception {
if(base64.contains("data:image")){
base64 = base64.substring(base64.indexOf(",")+1);
}
base64 = base64.toString().replace("\r\n", "");
File file = null;
//创建文件目录
String filePath=Const.TEMP_PATH;
File  dir=new File(filePath);
if (!dir.exists() && !dir.isDirectory()) {
dir.mkdirs();
}
BufferedOutputStream bos = null;
java.io.FileOutputStream fos = null;
try {
BASE64Decoder decoder = new BASE64Decoder();
byte[] bytes =  decoder.decodeBuffer(base64);
 
file=new File(filePath+Const.F+fileName);
OutputStream out = new FileOutputStream(filePath+Const.F+fileName);
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图片字符串和file之间互相转换,更多内容欢迎关注之后的文章

 

posted @ 2023-02-13 14:05  云豹科技-苏凌霄  阅读(51)  评论(0)    收藏  举报