java 图片url 转base64
时间: 2023-10-16 15:11:56 浏览: 116
java将图片转为base64返回给前端
5星 · 资源好评率100%
图片URL转为Base64的Java代码如下所示:
```java
String encoder = "data:image/jpg;base64,"; //定义图片类型,方便前端直接使用
ByteArrayOutputStream data = new ByteArrayOutputStream();
URL url = new URL(picUrl);//picUrl为图片地址
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
InputStream is = connection.getInputStream();
byte[] bytes = new byte[1024];
int len = 0;
while ((len = is.read(bytes)) != -1){
data.write(bytes,0,len);
}
is.close();
BASE64Encoder base64Encoder = new BASE64Encoder();
encoder = encoder + base64Encoder.encode(data.toByteArray()).replace("\r\n","").trim();
```
如果是本地图片,可以使用以下代码:
```java
String encoder = "data:image/jpg;base64,"; //定义图片类型,方便前端直接使用
ByteArrayOutputStream data = new ByteArrayOutputStream();
String filePath = "filePath";//这里的filePath为本地存放图片的地址
FileInputStream is = new FileInputStream(filePath);
byte[] bytes = new byte[1024];
int len = 0;
while ((len = is.read(bytes)) != -1){
data.write(bytes,0,len);
}
is.close();
BASE64Encoder base64Encoder = new BASE64Encoder();
encoder = encoder + base64Encoder.encode(data.toByteArray()).replace("\r\n","").trim();
```
希望对你有帮助!如果有任何其他问题,请随时提问。
阅读全文