PackageCom.net.util;ImportJava.io.FileInputStream;ImportJava.io.FileOutputStream;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.OutputStream;Importjavax.servlet.http.HttpServletRequest;ImportSun.misc.BASE64Decoder;ImportSun.misc.BASE64Encoder;/*** Picture Base64 transcoding Tool class *@authorZhangdi **/ Public classImagebase64util {/*** Images converted into base64 strings *@paramimgpath Picture Path *@return */ Public Staticstring Getimagestr (String imgpath) {//Converts a picture file into a byte array string and Base64 it for encodingString Imgfile =Imgpath; InputStream in=NULL; byte[] data =NULL; //reading a picture byte array Try{ in=NewFileInputStream (Imgfile); Data=New byte[In.available ()]; In.read (data); In.close (); } Catch(IOException e) {e.printstacktrace (); } //Base64 encoding of byte arraysBase64encoder encoder =NewBase64encoder (); //returns a BASE64 encoded byte array string returnEncoder.encode (data); } /*** Base64 strings into pictures *@paramimgstr Base64 String *@paramimgpath Picture Path *@return */ Public Static Booleangenerateimage (String imgstr,string imgpath,httpservletrequest request) {//get the path where the physical path WebAppString pathroot = Request.getsession (). Getservletcontext (). Getrealpath (""); //Base64 decoding a byte array string and generating a picture if(Imgstr = =NULL) return false; Base64decoder Decoder=NewBase64decoder (); Try { //Base64 decoding byte[] B =Decoder.decodebuffer (IMGSTR); for(inti = 0; i < b.length; ++i) {if(B[i] < 0) {//Adjust Exception DataB[i] + = 256; } } //Create a new pictureString Imgfilepath =pathroot+Imgpath; OutputStream out=NewFileOutputStream (Imgfilepath); Out.write (b); Out.flush (); Out.close (); return true; } Catch(Exception e) {return false; } }}
Base64 transcoding Java Edition