Java实现base64图片编码数据转换为本地图片的方法
本文实例讲述了Java实现base64图片编码数据转换为本地图片的方法。分享给大家供大家参考,具体如下:
项目中用到的把base64图片数据转为本地图片的函数
/**
*替换html中的base64图片数据为实际图片
*@paramhtml
*@paramfileRoot本地路径
*@paramserRoot服务器路径
*@return
*/
publicstaticStringreplaceBase64Image(Stringhtml,StringfileRoot,StringserRoot){
Filefile=newFile(fileRoot);
if(!file.exists()){//文件根目录不存在时创建
newFile(fileRoot).mkdirs();
}
StringhtmlContent=html;
Patternpattern=Pattern.compile("\\
]*src=\"data:image/[^>]*>");
Matchermatcher=pattern.matcher(html);
GUIDUtils.init();
while(matcher.find()){//找出base64图片元素
Stringstr=matcher.group();
Stringsrc=ExStringUtils.substringBetween(str,"src=\"","\"");//src="..."
Stringext=ExStringUtils.defaultIfEmpty(ExStringUtils.substringBetween(str,"data:image/",";"),"jpg");//图片后缀
Stringbase64ImgData=ExStringUtils.substringBetween(str,"base64,","\"");//图片数据
if(ExStringUtils.isNotBlank(ext)&&ExStringUtils.isNotBlank(base64ImgData)){
//data:image/gif;base64,base64编码的gif图片数据
//data:image/png;base64,base64编码的png图片数据
if("jpeg".equalsIgnoreCase(ext)){//data:image/jpeg;base64,base64编码的jpeg图片数据
ext="jpg";
}elseif("x-icon".equalsIgnoreCase(ext)){//data:image/x-icon;base64,base64编码的icon图片数据
ext="ico";
}
StringfileName=GUIDUtils.buildMd5GUID(false)+"."+ext;//待存储的文件名
StringfilePath=fileRoot+File.separator+fileName;//图片路径
try{
convertBase64DataToImage(base64ImgData,filePath);//转成文件
StringserPath=serRoot+fileName;//服务器地址
htmlContent=htmlContent.replace(src,serPath);//替换src为服务器地址
}catch(IOExceptione){
e.printStackTrace();
}
}
}
returnhtmlContent;
}
/**
*把base64图片数据转为本地图片
*@parambase64ImgData
*@paramfilePath
*@throwsIOException
*/
publicstaticvoidconvertBase64DataToImage(Stringbase64ImgData,StringfilePath)throwsIOException{
BASE64Decoderd=newBASE64Decoder();
byte[]bs=d.decodeBuffer(base64ImgData);
FileOutputStreamos=newFileOutputStream(filePath);
os.write(bs);
os.close();
}
PS:这里再为大家提供几款base64在线工具供大家参考:
BASE64编码解码工具:
http://tools.jb51.net/transcoding/base64
在线图片转换BASE64工具:
http://tools.jb51.net/transcoding/img2base64
Base64在线编码解码UTF-8版:
http://tools.jb51.net/tools/base64_decode-utf8.php
Base64在线编码解码gb2312版:
http://tools.jb51.net/tools/base64_decode-gb2312.php
更多关于java相关内容感兴趣的读者可查看本站专题:《Java编码操作技巧总结》、《Java数学运算技巧总结》、《Java数据结构与算法教程》、《Java字符与字符串操作技巧总结》、《Java操作DOM节点技巧总结》和《Java缓存操作技巧汇总》
希望本文所述对大家java程序设计有所帮助。