1 Package Com.*.util;2 3 import Java.io.FileInputStream;4 5 6 import Java.io.FileOutputStream;7 import java.io.IOException;8 import Java.io.InputStream;9 import Java.io.OutputStream;Ten import java.util.Date; One A import Decoder.base64decoder; - import Decoder.base64encoder; - the Public classBase64imgutils { - Public Static voidMain (string[] args) { -String strimg =getimagestr (); -System. out. println (STRIMG); + generateimage (strimg); - } + A /** at * Images converted into base64 strings - * Getimagestr - * August 31, 2016 afternoon 3:37:40 - * @param - * @return - */ in Public StaticString Getimagestr () {//Converts a picture file into a byte array string and Base64 it for encoding -String Imgfile ="d:/486e407765c21edd9cbffca69717efb1.jpg";//pictures to be processed toInputStreaminch=NULL; + byte[] data =NULL; - //reading a picture byte array the Try { * inch=NewFileInputStream (imgfile); $data =New byte[inch. Available ()];Panax Notoginseng inch. Read (data); - inch. Close (); the}Catch(IOException e) { + e.printstacktrace (); A } the //Base64 encoding of byte arrays +Base64encoder encoder =NewBase64encoder (); -String imghead="Data:image/jpg;base64,";//Head $ returnImghead+encoder.encode (data);//returns a BASE64 encoded byte array string $ } - - /** the * base64 strings into pictures - * GenerateimageWuyi * August 31, 2016 afternoon 3:33:12 the * @param - * @return Wu */ - Public StaticString Generateimage (String imgstr) {//Base64 decoding a byte array string and generating a picture About if(Imgstr = =NULL){//image data is empty $ return ""; - } -String ClassPath =NewBase64imgutils (). GetClass (). GetResource (""). GetPath (); -String Path = classpath.substring (0, Classpath.indexof ("Web-inf")); ASystem. out. println (path); +Base64decoder decoder =NewBase64decoder (); the Try { -String imghead=imgstr.substring (0, Imgstr.indexof (";"). Replace ("data:image/",".");//get the picture name extension $Imgstr=imgstr.substring (Imgstr.indexof (",")+1);//Picture Content the the //Base64 decoding the byte[] B =Decoder.decodebuffer (IMGSTR); the for(inti =0; i < b.length; ++i) { - if(B[i] <0) {//Adjust Exception Data inB[i] + = the; the } the } About //Create a JPEG picture theString filename="upload/"+NewDate (). GetTime () +imghead;//name theString Imgfilepath =path+"/"+filename;//the newly generated picture theOutputStream out=NewFileOutputStream (imgfilepath); + out. Write (b); - out. Flush (); the out. Close ();Bayi returnfilename; the}Catch(Exception e) { the return ""; - } - } the the the}
Interface Upload Base64 encoded image