/**
* 图片与Base64的转换工具
*
* @author: hubz
* @datetime: 2020/9/7 22:16
**/
import org.apache.commons.codec.binary.Base64;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class ImgAndBase64Utils{
public static void main(String[] args) throws IOException {
String imgPath = "src\\main\\resources\\imgs\\codeStream.jpg";
String base64Str = img2Base64String(imgPath);
String outPath = "src\\main\\resources\\imgs\\codeStream4.jpg";
Base64String2img(base64Str,outPath);
}
private static String img2Base64String(String imgPath) throws IOException {
byte[] imgBytes = Files.readAllBytes(Paths.get(imgPath));
return new String(Base64.encodeBase64(imgBytes));
}
private static void Base64String2img(String base64Str,String outPath) throws IOException {
byte[] imgBytes = Base64.decodeBase64(base64Str);
Files.write(Paths.get(outPath),imgBytes);
}
}