base64 字符串 转图片 保存到本地 java
时间: 2023-08-15 09:03:08 浏览: 114
可以使用 Java 的 Base64 类和 ImageIO 类来将 Base64 字符串转换为图片并保存到本地。以下是示例代码:
```java
import java.io.IOException;
import java.io.FileOutputStream;
import java.util.Base64;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
public class Base64ToImage {
public static void main(String[] args) throws IOException {
// Base64字符串
String base64String = "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAzUlEQVQ4T2NkoBAwUqifAFIyMDAwMDCwMzEwMjIysDAwMrFwMDAxMDEwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIzs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7OzszMzEyMzEyMzEyMzEyMzEyMzEyMzEyMzEyMzEyMzEyMzEyMzEyMzEyMzEyMzEyMzEyMzEyMzEyMzEyMzEyMbI0+IgAAACV0RVh0ZGF0ZTpjcmVhdGUAMjAyMC0wNi0xM1QxMDo1MTo0MSswMjowMKc9z1sAAAAldEVYdGRhdGU6bW9kaWZ5ADIwMjAtMDYtMTNUMTA6NTE6NDErMDI6MDBKt7AAAAAElFTkSuQmCC";
// 将 Base64 字符串解码为字节数组
byte[] imageBytes = Base64.getDecoder().decode(base64String);
// 将字节数组转换为 BufferedImage
BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageBytes));
// 将 BufferedImage 保存到本地
ImageIO.write(image, "png", new FileOutputStream("output.png"));
}
}
```
在上面的示例代码中,我们首先将 Base64 字符串解码为字节数组。然后,我们使用 ImageIO 类的 `read()` 方法将字节数组转换为 BufferedImage 对象。最后,我们使用 ImageIO 类的 `write()` 方法将 BufferedImage 对象保存到本地。
阅读全文