[Java] The conversion between picture and Base64

Source: Internet
Author: User
Tags base64

The function of this article is to convert local or online images into Base64 and base64 into pictures.

Well, not much to say, directly on the code!

Import Java.io.ByteArrayOutputStream;
Import Java.io.FileInputStream;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.OutputStream;
Import java.net.HttpURLConnection;
Import Java.net.URL;

Import Com.steward.utils.StringUtil;

Import Sun.misc.BASE64Decoder;
Import Sun.misc.BASE64Encoder;

@SuppressWarnings ("restriction")
public class Base64utils {

public static void Main (string[] args) throws Exception {

Local Image Address
String url = "C:/users/administrator/desktop/628947887489084892.jpg";
Online Image Address
String string = "Http://bpic.588ku.com//element_origin_min_pic/17/03/03/7bf4480888f35addcf2ce942701c728a.jpg";

String str = base64utils.imagetobase64bylocal (URL);

String ste = Base64utils.imagetobase64byonline (string);

System.out.println (str);

Base64utils.base64toimage (str, "c:/users/administrator/desktop/test1.jpg");

Base64utils.base64toimage (Ste, "c:/users/administrator/desktop/test2.jpg");
}

/**
* Local image converted to base64 string
* @param imgfile Picture Local Path
* @return
*
* @author ZHANGJL
* @dateTime 2018-02-23 14:40:46
*/
public static string Imagetobase64bylocal (String imgfile) {//Converts the picture file to a byte array string and encodes it Base64


InputStream in = null;
byte[] data = null;

Reading a picture byte array
try {
in = new FileInputStream (imgfile);

data = new byte[in.available ()];
In.read (data);
In.close ();
} catch (IOException e) {
E.printstacktrace ();
}
BASE64 encoding of byte arrays
Base64encoder encoder = new Base64encoder ();

return Encoder.encode (data);//returns BASE64 encoded byte array string
}



/**
* Online images converted into base64 strings
*
* @param imgurl Picture Line path
* @return
*
* @author ZHANGJL
* @dateTime 2018-02-23 14:43:18
*/
public static string Imagetobase64byonline (String imgurl) {
Bytearrayoutputstream data = new Bytearrayoutputstream ();
try {
Create URL
URL url = new URL (imgurl);
Byte[] by = new byte[1024];
Create a link
HttpURLConnection conn = (httpurlconnection) url.openconnection ();
Conn.setrequestmethod ("GET");
Conn.setconnecttimeout (5000);
InputStream is = Conn.getinputstream ();
Reads the content in memory
int len =-1;
while (len = Is.read (by))! =-1) {
Data.write (by, 0, Len);
}
Close the stream
Is.close ();
} catch (IOException e) {
E.printstacktrace ();
}
BASE64 encoding of byte arrays
Base64encoder encoder = new Base64encoder ();
Return Encoder.encode (Data.tobytearray ());
}


/**
* Base64 string converted to picture
* @param imgstr Base64 string
* @param imgfilepath Picture Storage path
* @return
*
* @author ZHANGJL
* @dateTime 2018-02-23 14:42:17
*/
public static Boolean Base64toimage (String imgstr,string imgfilepath) {//Base64 decoding of byte array strings and generating pictures

if (Stringutil.isempty (IMGSTR))//image data is empty
return false;

Base64decoder decoder = new Base64decoder ();
try {
Base64 decoding
Byte[] B = Decoder.decodebuffer (IMGSTR);
for (int i = 0; i < b.length; ++i) {
if (B[i] < 0) {//Adjust exception data
B[i] + = 256;
}
}

OutputStream out = new FileOutputStream (Imgfilepath);
Out.write (b);
Out.flush ();
Out.close ();

return true;
} catch (Exception e) {
return false;
}

}


}

      

One of the

if (Stringutil.isempty (IMGSTR))//image data is empty
return false;

Just to determine if the incoming data is empty, the inside judgment is simple

/**
* Verify that the string is empty
*
* @param input
* @return
*/
public static Boolean isEmpty (String input) {
return input = = NULL | | Input.equals ("") | | Input.matches (Empty_regex);
}

[Java] The conversion between picture and Base64

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.