之前遇到的小问题,记录一下,仅此而已。
```
private static String imgToBase64(String path) {
try {
HttpResponse response = HttpRequest.get(path).execute();
if ( null == response) {
throw new BizException(CosmosResultCodeEnum.BIZ_FAIL);
}
return "data:image/jpeg;base64," + Base64.encodeBase64String(response.bodyBytes());
} catch (Exception e) {
throw new BuisnessException(CosmosResultCodeEnum.BIZ_FAIL);
}
}
```
# 20220902更新 base64转 图片
**注意!我们将图片转为 base64 的时候数据前面添加了 `data:image/png;base64,` 这种格式,在转图片时需要将其删掉,不然就会报错。**
```java
if (base64Data.startsWith("data:image/png;base64,")) {
base64Data = base64Data.replace("data:image/png;base64,", "");
} else if (base64Data.startsWith("data:image/jpeg;base64,")) {
base64Data = base64Data.replace("data:image/jpeg;base64,", "");
} else if (base64Data.startsWith("data:image/jpg;base64,")) {
base64Data = base64Data.replace("data:image/jpg;base64,", "");
}
```
```java
/**
* 将 base64 转为图片,并保存到指定位置
* @param base64 图片数据
* @param filePath 保存位置及文件名
* @throws IOException
*/
private static void base64ToImg(String base64, String filePath) throws IOException {
byte[] bs = new byte[1024];
bs = Base64.getDecoder().decode(base64);
BufferedOutputStream bos = null;
FileOutputStream fos = null;
File file = null;
file = new File(filePath);
try {
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(bs);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
```

图片转为 base64编码