package com.test;
import sun.misc.BASE64Encoder;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Base64;
public class imageBase64String {
public static String imageUrlToBase64(String imgUrl) {
URL url = null;
InputStream is = null;
ByteArrayOutputStream outStream = null;
HttpURLConnection httpUrl = null;
try {
url = new URL(imgUrl);
httpUrl = (HttpURLConnection) url.openConnection();
httpUrl.connect();
httpUrl.getInputStream();
is = httpUrl.getInputStream();
outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while( (len = is.read(buffer)) != -1 ){
outStream.write(buffer, 0, len);
}
return encode(outStream.toByteArray());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(is != null) {
is.close();
}
if(outStream != null) {
outStream.close();
}
if(httpUrl != null) {
httpUrl.disconnect();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
public static String encode(byte[] image){
BASE64Encoder decoder = new BASE64Encoder();
return replaceEnter(decoder.encode(image));
}
public static String replaceEnter(String str){
String reg ="[\n-\r]";
Pattern p = Pattern.compile(reg);
Matcher m = p.matcher(str);
return m.replaceAll("");
}
public static void main(String[] args) throws IOException {
String img=imageBase64String.imageUrlToBase64("https://myuat.xxxx.com/CreateCptBarCode?barType=-1&capitalid=152");
FileOutputStream outputStream = null;
try {
Base64.Decoder decoder = Base64.getDecoder();
byte[] bytes = decoder.decode(img);
outputStream = new FileOutputStream("C:\\Users\\h400175\\Desktop\\emp.jpg");
outputStream.write(bytes);
} catch (Exception e) {
e.printStackTrace();
}finally {
outputStream.close();
}
}
}