Java implements a conversion between a picture and a base64 string

Source: Internet
Author: User

   Java implements a conversion between a picture and a base64 string


Packagecom.zxc.testjava.ant;ImportJava.io.FileInputStream;ImportJava.io.FileOutputStream;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.OutputStream;ImportSun.misc.BASE64Decoder;ImportSun.misc.BASE64Encoder; Public classTestchangeimage { Public Static voidMain (string[] args) {String strimg=Getimagestr (); System.out.println (STRIMG); Generateimage (strimg);}//Convert images into base64 strings Public StaticString Getimagestr () {//Converts a picture file into a byte array string and Base64 it for encodingString imgfile = "C:/users/star/desktop/test.png";//pictures to be processedInputStream in =NULL;byte[] data =NULL;//reading a picture byte arrayTry{ in=NewFileInputStream (imgfile);d ATA=New byte[In.available ()];in.read (data); In.close ();} Catch(IOException e) {e.printstacktrace ();}//Base64 encoding of byte arraysBase64encoder encoder =NewBase64encoder ();returnEncoder.encode (data);//returns a BASE64 encoded byte array string}//base64 strings into pictures Public Static BooleanGenerateimage (String imgstr) {//Base64 decoding a byte array string and generating a pictureif(Imgstr = =NULL)//image data is emptyreturn false; Base64decoder Decoder=NewBase64decoder ();Try {//Base64 decodingbyte[] B =Decoder.decodebuffer (IMGSTR); for(inti = 0; i < b.length; ++i) {if(B[i] < 0) {//Adjust Exception DataB[i] + = 256;}}//Create a JPEG pictureString Imgfilepath = "C:/users/star/desktop/test22.png";//the newly generated pictureOutputStream out =NewFileOutputStream (Imgfilepath); Out.write (b); Out.flush (); Out.close ();return true;} Catch(Exception e) {return false;}}}

Java implements a conversion between a picture and a base64 string

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.