base64 转换为图片,并保存到本地目录

110 阅读1分钟
/**
 * base64 转换为图片,并保存到本地目录
 * @param base64Image  base64参数
 * @param imageName 图片名称前缀
 * @return 返回实际图片名称
 */
@NotNull
private String base64ToImageAndSaveLocal(String base64Image, String imageName) {
    File folder = new File(folderPath);

    if (!folder.exists()) { // 检查文件夹是否存在
        boolean created = folder.mkdirs(); // 递归创建文件夹
        if (created) {
            log.info(folderPath+" 目录创建成功");
        } else {
            throw new CustomException(folderPath+" 目录创建失败");
        }
    }
    String imgName =  imageName +"-"+System.currentTimeMillis()+".jpg";
    String absolutePath = folderPath +imgName; // 保存图片的路径及文件名

    try {
        //去掉image=
        if(base64Image.contains("base64")){
            //取 data:image/jpeg;base64, 之后的真正base64数据
            base64Image = base64Image.substring(base64Image.indexOf("base64,")+7);
        }
        byte[] imageData = Base64.decode(base64Image);

        FileOutputStream imageOutFile = new FileOutputStream(absolutePath);
        imageOutFile.write(imageData);

        imageOutFile.close();
    } catch (Exception e) {
        throw new CustomException("识别图片存储错误:" + e.getMessage());
    }
    return imgName;
}