Base64 jar包下载地址:http://download.csdn.net/detail/u010339699/5383203
public static void main(String[] args) {
String base64Img = null;
try {
base64Img = GetUrlImageToBase64("http://i4.qhimg.com/dr/270_500_/t019e5e3b6849035f6d.jpg");
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(base64Img);
}
/**
* 获取网络图片并转为Base64编码
*
* @param url
* 网络图片路径
* @return base64编码
* @throws Exception
*/
public static String GetUrlImageToBase64(String url) throws Exception {
if (url == null || "".equals(url.trim()))
return null;
URL u = new URL(url);
// 打开图片路径
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
// 设置请求方式为GET
conn.setRequestMethod("GET");
// 设置超时响应时间为5秒
conn.setConnectTimeout(5000);
// 通过输入流获取图片数据
InputStream inStream = conn.getInputStream();
// 读取图片字节数组
byte[] data = new byte[inStream.available()];
inStream.read(data);
inStream.close();
// 对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
// 返回Base64编码过的字节数组字符串
return encoder.encode(data);
}