Base64码转化为图片
Base64Decoder
package com.example.pdfdemo.utils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Base64;
public class Base64DecoderUtils {
/**
* @Author: gakki
* @Description: base64转图片
* @Date: 2021/06/16 00:01
* @Param: [base64String(base64码), imgPath(保存图片路径)]
* @return: Boolean
**/
public static void Base64Decoder(String base64String,String imgPath) throws IOException {
//拿到解码器
Base64.Decoder decoder = Base64.getDecoder();
//进行解码 存到byte数组
byte[] data = decoder.decode(base64String);
//新建文件流对象
FileOutputStream fos = new FileOutputStream(new File(imgPath));
//写入文件
fos.write(data);
//清空缓冲区数据
fos.flush();
fos.close();
}
}
图片转化为Base64码
Base64Encoder
package com.example.pdfdemo.utils;
import java.io.*;
import java.util.Base64;
public class Base64EncoderUtils {
/**
* @Author: gakki
* @Description: 图片转Base64码
* @Date: 2021/06/16 00:04
* @Param: [PhotoPath(图片路径)]
* @return: String
**/
public static String Base64Encoder(String PhotoPath) throws IOException {
//获取文件对象
File file = new File(PhotoPath);
//获取文件流
FileInputStream fis = new FileInputStream(file);
//拿到文件流长度并且new byte数组
int length = fis.available();
byte[] data = new byte[length];
//读取
fis.read(data);
fis.close();
//获取编码对象
Base64.Encoder encoder = Base64.getEncoder();
//进行编码
String string = encoder.encodeToString(data);
return string;
}
}
前缀:data:image/jpeg;base64