需求:通过url从服务器上获取图片,将图片转换成base64的字符串用来做业务。
代码:
package com.su.mybatis.oracle.controller;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.commons.codec.binary.Base64;
public class Test {
public static void main(String[] args) {
String imageBase64 = "";
String path = "xxxxxxx";//图片url
try {
imageBase64 = getImageByPath(path);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(imageBase64);
//TODO 做自己的业务
}
public static String getImageByPath(String path) throws IOException {
URL url = null;
HttpURLConnection httpUrl = null;
InputStream in = null;
byte[] data = null;
try {
url = new URL(path);
httpUrl = (HttpURLConnection) url.openConnection();
httpUrl.connect();
in = httpUrl.getInputStream();
data = new byte[in.available()];
in.read(data);
} catch (IOException e) {
e.printStackTrace();
} finally {
if(in != null)
in.close();
}
return data == null ? "" : Base64.encodeBase64String(data);
}
}
如果有写的不对的地方,请大家多多批评指正,非常感谢!