怎么在Java中将base64图片编码数据转换为本地图片?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
Java的特点有哪些 1.Java语言作为静态面向对象编程语言的代表,实现了面向对象理论,允许程序员以优雅的思维方式进行复杂的编程。 2.Java具有简单性、面向对象、分布式、安全性、平台独立与可移植性、动态性等特点。 3.使用Java可以编写桌面应用程序、Web应用程序、分布式系统和嵌入式系统应用程序等。
/**
* 替换html中的base64图片数据为实际图片
* @param html
* @param fileRoot 本地路径
* @param serRoot 服务器路径
* @return
*/
public static String replaceBase64Image(String html,String fileRoot,String serRoot){
File file = new File(fileRoot);
if(!file.exists()){//文件根目录不存在时创建
new File(fileRoot).mkdirs();
}
String htmlContent = html;
Pattern pattern = Pattern.compile("\\<img[^>]*src=\"data:image/[^>]*>");
Matcher matcher = pattern.matcher(html);
GUIDUtils.init();
while(matcher.find()){ //找出base64图片元素
String str = matcher.group();
String src = ExStringUtils.substringBetween(str, "src=\"", "\"");//src="..."
String ext = ExStringUtils.defaultIfEmpty(ExStringUtils.substringBetween(str, "data:image/", ";"), "jpg");//图片后缀
String base64ImgData = 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";
} else if("x-icon".equalsIgnoreCase(ext)){//data:image/x-icon;base64,base64编码的icon图片数据
ext = "ico";
}
String fileName = GUIDUtils.buildMd5GUID(false)+"."+ext;//待存储的文件名
String filePath = fileRoot+File.separator+fileName;//图片路径
try {
convertBase64DataToImage(base64ImgData, filePath);//转成文件
String serPath = serRoot+fileName;//服务器地址
htmlContent = htmlContent.replace(src, serPath);//替换src为服务器地址
} catch (IOException e) {
e.printStackTrace();
}
}
}
return htmlContent;
}
/**
* 把base64图片数据转为本地图片
* @param base64ImgData
* @param filePath
* @throws IOException
*/
public static void convertBase64DataToImage(String base64ImgData,String filePath) throws IOException {
BASE64Decoder d = new BASE64Decoder();
byte[] bs = d.decodeBuffer(base64ImgData);
FileOutputStream os = new FileOutputStream(filePath);
os.write(bs);
os.close();
}
看完上述内容,你们掌握怎么在Java中将base64图片编码数据转换为本地图片的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。