A function used in a project to convert Base64 picture data to a local picture
/** * Replaces base64 picture data in HTML for actual picture * @param HTML * @param fileroot Local Path * @param serroot Server path * @return/Public
static string Replacebase64image (String html,string fileroot,string serroot) {File File = new File (fileroot);
Create new file (Fileroot) if (!file.exists ()) {//file root does not exist. Mkdirs ();
} String htmlcontent = html;
Pattern pattern = pattern.compile ("\\]*src=\" data:image/[^>]*>);
Matcher Matcher = pattern.matcher (HTML);
Guidutils.init ();
while (Matcher.find ()) {//Find base64 picture element String str = Matcher.group ();
String src = exstringutils.substringbetween (str, "src=\", "\");//src= "..." String ext = exstringutils.defaultifempty (Exstringutils.substringbetween (str, "data:image/", ";"), "JPG");//Picture suffix str ing base64imgdata = exstringutils.substringbetween (str, "base64,", "\");//Picture data if (Exstringutils.isnotblank (EXT) &&exstringutils.isnotblank (Base64imgdata)) {//DATA:IMAGE/GIF;BASE64,BASE64 encoded GIF image data//data:image/pngBASE64,BASE64 encoded PNG picture data if ("JPEG". Equalsignorecase (EXT)) {//DATA:IMAGE/JPEG;BASE64,BASE64 encoded JPEG image data ext = "JPG";
else if ("X-icon". Equalsignorecase (EXT)) {//DATA:IMAGE/X-ICON;BASE64,BASE64 encoded icon image data Ext = "ico"; String FileName = Guidutils.buildmd5guid (false) + "." +ext;//the filename to be stored String filePath = fileroot+file.separator+filename;//picture path try {convertbase64datatoimage (base6 4ImgData, FilePath)//Convert to file String Serpath = serroot+filename;//server Address htmlcontent = htmlcontent.replace (src, SerP
ATH);//replace SRC for server address} catch (IOException e) {e.printstacktrace ();
}} return htmlcontent; /** * Convert base64 picture data to local image * @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 (); }