图片转Base64的分析理解(仅个人学习使用,有错误也希望提出指正)
//编码器
private final static Encoder encoder = Base64.getEncoder();
//解码器
private final static Decoder decoder = Base64.getDecoder();
将网络图片转base64
public static String NetImageToBase64(String netImagePath) {
final ByteArrayOutputStream data = new ByteArrayOutputStream();
InputStream is = null;
try {
// 创建URL
URL url = new URL(netImagePath);
final byte[] by = new byte[1024];
// 创建链接
final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
is = conn.getInputStream();
// 将内容读取内存中
int len = -1;
while ((len = is.read(by)) != -1) {
data.write(by, 0, len);
}
conn.disconnect();
return encoder.encodeToString(data.toByteArray());
} catch (IOException e) {
new RuntimeException("网络图片转换Base64异常:", e);
} finally {
// 关闭流
if (is != null) {
try {
is.close();
} catch (IOException e) {
new RuntimeException("[NetImageToBase64方法执行fail]",e);
}
}
}
return null;
}
将本地图片转base64
public static String ImageToBase64(String imgPath) {
byte[] data = null;
InputStream is = null;
// 读取图片字节数组
try {
is = new FileInputStream(imgPath);
data = new byte[is.available()];
is.read(data);
// 返回Base64编码过的字节数组字符串
String imgBase64Str = encoder.encodeToString(Objects.requireNonNull(data));
return imgBase64Str;
} catch (IOException e) {
new RuntimeException("本地图片转换Base64异常:", e);
} finally {
// 关闭流
if (is != null) {
try {
is.close();
} catch (IOException e) {
new RuntimeException("[ImageToBase64 fail]",e);
}
}
}
return null;
}