Objective:
Environment: Before using this code: Make sure your JDK is JAVA8 and above
Dev Test Address: http://imgbase64.duoshitong.com/to see if the execution was successful
Precautions:
The generic plug-in Returns a base64 encoded string that has a prefix. "Data:image/jpeg;base64," this has to be removed before decoding.
Code:
Maintest
1 /**2 * Example3 * @throwsunsupportedencodingexception4 * @throwsFileNotFoundException5 */6@SuppressWarnings ("Resource")7 Public Static voidMain (string[] args)throwsunsupportedencodingexception, FileNotFoundException {8String strimg = getimagestr ("z:\\ watermark \\2.bmp");9 System.out.println (strimg);TenFile File =NewFile ("Z://1.txt"); OneFileOutputStream fos =Newfileoutputstream (file); AOutputStreamWriter OSW =NewOutputStreamWriter (FOS, "UTF-8"); - Try { - Osw.write (strimg); the}Catch(IOException e) { - //TODO auto-generated Catch block - e.printstacktrace (); - } + //generateimage (strimg, "z:\\ watermark \\444.bmp"); - +}
Encryption:
1**2*@Description: Converting from image address to Base64 encoded string3*@Author:4*@CreateTime:5* @return6*/7 Public Staticstring Getimagestr (String imgfile) {8InputStream InputStream =NULL;9 byte[] data =NULL;Ten Try { OneInputStream =NewFileInputStream (imgfile); Adata =New byte[Inputstream.available ()]; - inputstream.read (data); - inputstream.close (); the}Catch(IOException e) { - e.printstacktrace (); - } - //Encrypt +Encoder Encoder =Base64.getencoder (); - returnencoder.encodetostring (data); +}
Decrypt:
1 /**2 * @Description: Convert base64 encoded string to picture3 * @Author:4 * @CreateTime:5 * @paramIMGSTR Base64 Encoded string6 * @parampath picture paths-specific to file7 * @return8 */9 Public Static Booleangenerateimage (String imgstr, String path) {Ten if(Imgstr = =NULL) One return false; A //decryption - Try { -Decoder Decoder =Base64.getdecoder (); the byte[] B =Decoder.decode (IMGSTR); - //working with Data - for(inti = 0; i < b.length; ++i) { - if(B[i] < 0) { +B[i] + = 256; - } + } AOutputStream out =NewFileOutputStream (path); at Out.write (b); - Out.flush (); - out.close (); - return true; -}Catch(IOException e) { - return false; in } -}
Java processing Picture base64 encoding for mutual conversion