jsp将图片转为base64
时间: 2023-11-28 21:03:37 浏览: 164
图片转base64
4星 · 用户满意度95%
可以使用Java的Base64类将图片转为base64编码。以下是一个示例代码:
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Base64;
public class ImageToBase64 {
public static void main(String[] args) {
String imagePath = "path/to/image.jpg";
String base64Image = getImageAsBase64(imagePath);
System.out.println(base64Image);
}
private static String getImageAsBase64(String imagePath) {
File file = new File(imagePath);
try (FileInputStream imageInFile = new FileInputStream(file)) {
byte[] imageData = new byte[(int) file.length()];
imageInFile.read(imageData);
return Base64.getEncoder().encodeToString(imageData);
} catch (IOException e) {
System.out.println("Error while reading image");
return null;
}
}
}
```
阅读全文