功能需求:将网络图片转换为base64字符串传给前端
lg:String url = "https://www.baidu.com/369270f.jpg";
base64转码之后:
url = "/9j/4AAQSkZJRg......G9AFqq6";
代码实现:
package test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import sun.misc.BASE64Encoder;
public class Base64Util {
public static void main(String[] args) {
String filePath = "https://www.baidu.com/369270f.jpg";//待处理的图片
System.out.println(GetImageStrFromUrl(filePath));//转换后的base64字符串
}
/**
* 将一张网络图片转化成Base64字符串
* @param imgURL
* @return
*/
public static String GetImageStrFromUrl(String imgURL) {
ByteArrayOutputStream data = new ByteArrayOutputStream();
try {
// 创建URL
URL url = new URL(imgURL);
byte[] by = new byte[1024];
// 创建链接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
InputStream is = conn.getInputStream();
// 将内容读取内存中
int len = -1;
while ((len = is.read(by)) != -1) {
data.write(by, 0, len);
}
// 关闭流
is.close();
} catch (IOException e) {
e.printStackTrace();
}
// 对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data.toByteArray());
}
}
如果需要在转换工具中检验是否转换成功,则需要在转换后的编码前面加:"data:image/jpg;base64, "