JAVA base 64工具类_java base64工具类 保存图片

该方法用于base64解码,并存储图片

// 图片路劲层级分隔符

private static String separator = "/";

public String saveImg(String baseImg,String saveName) throws Base64DecodingException {

//定义一个正则表达式的筛选规则,为了获取图片的类型

String rgex = "data:image/(.*?);base64";

String type = getSubUtilSimple(baseImg, rgex);

//去除base64图片的前缀

baseImg = baseImg.replaceFirst("data:(.+?);base64,", "");

byte[] b;

byte[] bs;

OutputStream os = null;

String fileName = "";

//把图片转换成二进制

b = Base64.decode(baseImg.replaceAll(" ", "+"));

//生成路径

//获取项目classes/static的地址

String staticPath = ClassUtils.getDefaultClassLoader().getResource("static").getPath();

//文件名称

String uploadFileName = UUID.randomUUID().toString();

// 图片存储目录及图片名称

String url_path = "img" + File.separator;

//图片保存路径

String path = staticPath + File.separator + url_path;

// 访问路径=静态资源路径+文件目录路径

String visitPath ="static/" + url_path;

//随机生成图片的名字,同时根据类型结尾

fileName = saveName + "." + type;

File file = new File(path);

if (!file.exists() && !file.isDirectory()) {

file.mkdirs();

}

File imageFile = new File(path + "/" + fileName);

BASE64Decoder d = new BASE64Decoder();

// 保存

try {

bs = d.decodeBuffer(Base64.encode(b));

os = new FileOutputStream(imageFile);

os.write(bs);

} catch (IOException e) {

e.printStackTrace();

}finally {

if (os != null) {

try {

os.close();

} catch (IOException e) {

e.getLocalizedMessage();

}

}

}

return "img" + separator + fileName;

}

————————————————————上文出自胖胖,转载请附带原文链接

后续更新自学的方法,以及java知识总结

我是哪怕前路坎坷,也不愿负年轻的菜狗,自学之路,共勉

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值