Picture and Base64 encoded strings convert each other, and the picture and byte arrays convert each other

Source: Internet
Author: User
Tags base64

Convert images and Base64 encoded strings to each other

ImportSun.misc.BASE64Decoder;ImportSun.misc.BASE64Encoder;ImportJava.io.*;/** * @authorLishupeng * @create 2017-05-06 pm 2:56 **/ Public classBase64test { 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\\administrator\\desktop\\a\\1.png";//pictures to be processedInputStream 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 (); 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 picture        if(Imgstr = =NULL)//image data is empty            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 JPEG pictureString Imgfilepath = "D://222.jpg";//the newly generated pictureOutputStream out =NewFileOutputStream (Imgfilepath);            Out.write (b);            Out.flush ();            Out.close (); return true; } Catch(Exception e) {return false; }    }

Picture and byte arrays convert each other

ImportJavax.imageio.stream.FileImageInputStream;ImportJavax.imageio.stream.FileImageOutputStream;ImportJava.io.ByteArrayOutputStream;ImportJava.io.File;Importjava.io.FileNotFoundException;Importjava.io.IOException;/** * @authorLishupeng * @create 2017-05-06 pm 3:48 **/ Public classImage2byte { Public Static voidMain (string[] args) {byte[] data = Image2byte ("C:\\users\\administrator\\desktop\\a\\1.png"));        System.out.println (Data.tostring ()); Byte2image (data,"D://222.jpg"); }    //picture to byte array     Public Static  byte[] image2byte (String path) {byte[] data =NULL; Fileimageinputstream input=NULL; Try{input=NewFileimageinputstream (NewFile (path)); Bytearrayoutputstream Output=NewBytearrayoutputstream (); byte[] buf =New byte[1024]; intNumbytesread = 0;  while((Numbytesread = Input.read (BUF))! =-1) {output.write (buf,0, Numbytesread); } Data=Output.tobytearray ();            Output.close ();        Input.close (); } Catch(FileNotFoundException ex1) {ex1.printstacktrace (); } Catch(IOException ex1) {ex1.printstacktrace (); }        returndata; }    //byte array to picture     Public Static voidByte2image (byte[] data, String path) {        if(Data.length < 3 | | path.equals (""))return; Try{fileimageoutputstream Imageoutput=NewFileimageoutputstream (NewFile (path)); Imageoutput.write (data,0, data.length);            Imageoutput.close (); System.out.println (Make picture success,please find image in "+path); } Catch(Exception ex) {System.out.println ("Exception:" +ex);        Ex.printstacktrace (); }    }    //byte array to 16 binary string     PublicString byte2string (byte[] data) {        if(Data = =NULL|| Data.length <= 1)return"0x"; if(Data.length > 200000)return"0x"; StringBuffer SB=NewStringBuffer (); intBuf[] =New int[Data.length]; //byte array converted to decimal         for(intk = 0; K < Data.length; k++) {Buf[k]= Data[k] < 0? (Data[k] + 256): (Data[k]); }        //decimal into hexadecimal         for(intk = 0; K < Buf.length; k++) {            if(Buf[k] <) sb.append ("0" +integer.tohexstring (Buf[k])); Elsesb.append (integer.tohexstring (buf[k)); }        return"0x" +sb.tostring (). toUpperCase (); }}

Picture and Base64 encoded strings are converted to each other, and images and byte arrays are converted to each other

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.