freemarker生成文档时如何把图片转成base64的Java代码
时间: 2024-04-20 13:06:48 浏览: 191
可以使用Java的Base64类来将图片转换为Base64编码字符串。以下是一个示例代码片段,可以将图片转换为Base64编码字符串并将其插入到Freemarker模板中。
```java
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Base64;
public class ImageToBase64 {
public static String convertImageToBase64(String imagePath) throws IOException {
File file = new File(imagePath);
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int count = 0;
while ((count = fis.read(buffer)) != -1) {
baos.write(buffer, 0, count);
}
byte[] imageBytes = baos.toByteArray();
String base64Image = Base64.getEncoder().encodeToString(imageBytes);
fis.close();
baos.close();
return base64Image;
}
}
```
在Freemarker模板中,使用以下代码将Base64编码的图片插入到HTML代码中。
```html
<img src="data:image/png;base64,${imageBase64}" alt="image">
```
其中,`${imageBase64}`是上述Java代码中返回的Base64编码字符串。注意,这里的`image/png`应该替换为你实际使用的图片类型。
阅读全文
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)