java下载base64图片
时间: 2023-05-23 14:02:11 浏览: 436
Base64+JSON实现图片下载
可以使用 Java 的 URL 和 HttpURLConnection 对象来下载 base64 图片:
```java
import java.net.URL;
import java.net.HttpURLConnection;
import java.util.Base64;
public class DownloadBase64Image {
public static void main(String[] args) throws Exception {
String base64 = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAACjElEQVR4nK2TwW4bRxiHn7MvkNLdPnj9klvX8SQ31WKNhe1EiFQVNk..."; // base64 string
String[] parts = base64.split(",");
String contentType = parts[0].split(";")[0].split(":")[1];
String imageData = parts[1];
byte[] decoded = Base64.getDecoder().decode(imageData.getBytes());
URL url = new URL("https://example.com/image.png");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("PUT");
connection.setRequestProperty("Content-Type", contentType);
connection.setRequestProperty("Content-Length", String.valueOf(decoded.length));
connection.setDoOutput(true);
connection.getOutputStream().write(decoded);
int responseCode = connection.getResponseCode();
System.out.println("Response Code : " + responseCode);
}
}
```
这个程序将从 base64 图片中提取图片数据并使用 HttpURLConnection 将其上传到指定的 URL。你需要替换 url 和 content-type,以确保这个程序运行在你的环境中。
阅读全文