本文實例講述了Java實現(xiàn)base64圖片編碼數(shù)據(jù)轉(zhuǎn)換為本地圖片的方法。分享給大家供大家參考,具體如下:
項目中用到的把base64圖片數(shù)據(jù)轉(zhuǎn)為本地圖片的函數(shù)
/*** 替換html中的base64圖片數(shù)據(jù)為實際圖片* @param html* @param fileRoot 本地路徑* @param serRoot 服務(wù)器路徑* @return*/public static String replaceBase64Image(String html,String fileRoot,String serRoot){ File file = new File(fileRoot); if(!file.exists()){//文件根目錄不存在時創(chuàng)建 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,", "/"");//圖片數(shù)據(jù) if(ExStringUtils.isNotBlank(ext)&&ExStringUtils.isNotBlank(base64ImgData)){ //data:image/gif;base64,base64編碼的gif圖片數(shù)據(jù) //data:image/png;base64,base64編碼的png圖片數(shù)據(jù) if("jpeg".equalsIgnoreCase(ext)){//data:image/jpeg;base64,base64編碼的jpeg圖片數(shù)據(jù) ext = "jpg"; } else if("x-icon".equalsIgnoreCase(ext)){//data:image/x-icon;base64,base64編碼的icon圖片數(shù)據(jù) ext = "ico"; } String fileName = GUIDUtils.buildMd5GUID(false)+"."+ext;//待存儲的文件名 String filePath = fileRoot+File.separator+fileName;//圖片路徑 try { convertBase64DataToImage(base64ImgData, filePath);//轉(zhuǎn)成文件 String serPath = serRoot+fileName;//服務(wù)器地址 htmlContent = htmlContent.replace(src, serPath);//替換src為服務(wù)器地址 } catch (IOException e) { e.printStackTrace(); } } } return htmlContent;}/*** 把base64圖片數(shù)據(jù)轉(zhuǎn)為本地圖片* @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程序設(shè)計有所幫助。
新聞熱點
疑難解答
圖片精選