java 图片转base64

/**
* 将网络图片转成Base64码,此方法可以解决解码后图片显示不完整的问题
* @param imgURL图片地址。
* 例如:http://***.com/271025191524034.jpg
* @return
*/
public static String imgBase64(String imgURL) {
ByteArrayOutputStream outPut = new ByteArrayOutputStream();
byte[] data = new byte[1024];
try {
// 创建URL
URL url = new URL(imgURL);
// 创建链接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(10 * 1000);

if(conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "fail";//连接失败/链接失效/图片不存在
}
InputStream inStream = conn.getInputStream();
int len = -1;
while ((len = inStream.read(data)) != -1) {
outPut.write(data, 0, len);
}
inStream.close();
} catch (IOException e) {
e.printStackTrace();
}
// 对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(outPut.toByteArray());
}

posted on 2020-09-21 18:08  博客园197  阅读(417)  评论(0编辑  收藏  举报