String content = "";//普通字符串
// 创建一个 Base64 编码器
BASE64Encoder base64Encoder = new BASE64Encoder();
// 执行 Base64 编码操作
byte[] bytes = content.getBytes("UTF-8");
String encodedString = base64Encoder.encode(bytes);
或
byte[] bytes = null;
String base64Image = new String(Base64.encodeBase64(bytes));
智慧汽车装车项目示例:
@Override
public AjaxResult updateImage2(String req) throws Exception {
String filePath = "D:\\图片\\123XX_456XX_20240305\\1_SCBU4578633.jpg"; // 指定要转换的文件路径
File imageFile = new File(filePath);
InputStream inputStream = new FileInputStream(imageFile);
byte[] buffer = new byte[(int) imageFile.length()];
int bytesRead = inputStream.read(buffer);
if (bytesRead != -1) {
String base64Image = new String(Base64.encodeBase64(buffer));
System.out.println(base64Image);
return AjaxResult.success("图片二进制字符串",base64Image);
} else {
throw new IOException("Failed to read the file.");
}
}