在项目终于到本地存储的照片文件,并且该服务器上没有网络的情况,就需要根据嫌贵路径获取到照片,并转换成base64编码使用
Java提供了丰富的 I/O 类库,可以轻松读取文件内容。
常用的类:
- FileInputStream:用于读取文件的二进制数据
- BufferedInputStream:对输入流进行缓冲,提升读取效率
- Files 类:Java NIO 提供的工具类,可以一次性读取整个文件为字节数组(适用于文件较小的情况)
从 Java 8 开始,Java 内置了 Base64 编码与解码的支持,位于 java.util.Base64 包中。
常用方法:
- Base64.getEncoder().encodeToString(byte[] src):将字节数组转换为 Base64 编码的字符串
- Base64.getDecoder().decode(String src):将 Base64 字符串解码为原始的字节数组
代码示例
java
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Base64;
/**
* ImageToBase64 类实现了将图片文件转换为 Base64 编码字符串的功能。
* 该程序通过读取图片文件的二进制数据,再利用 Java 内置 Base64 编码器进行编码,
* 最终生成可嵌入到 HTML、JSON 或其他数据传输格式中的 Base64 字符串。
*/
public class Base64Util {
/**
* 根据本地照片路径获取base64照片
* @param imagePath 图片路径
* @return base64图片
*/
public static String image2Base64(String imagePath) {
// 定义字节数组,用于存储图片数据
byte[] imageBytes = null;
try {
File file = new File(imagePath);
//使用 FileInputStream 读取文件
FileInputStream imageInFile = new FileInputStream(file);
imageData[] = new byte[(int) new File(imagePath).length()];
imageInFile.read(imageData);
// 使用Base64编码图片数据
String encodedImage = Base64.encodeBase64String(imageData);
System.out.println(encodedImage);
imageInFile.close();
return encodedImage;
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
/**
* 将指定路径的图片转换为 Base64 编码
* @param imagePath 图片文件路径(/home/files/2025-04-01/a2dbdd2836c245bd80c00aceb562b232.jepg)
* @return base64图片
*/
public static String image2Base641(String imagePath) {
// 定义字节数组,用于存储图片数据
byte[] imageBytes = null;
try {
// 使用 Files.readAllBytes() 读取文件内容
File file = new File(imagePath);
imageBytes = Files.readAllBytes(file.toPath());
} catch (IOException e) {
// 输出错误信息,并返回 null
e.printStackTrace();
return null;
}
// 利用 Base64 编码器将图片数据转换为字符串
String base64String = Base64.getEncoder().encodeToString(imageBytes);
return base64String;
}
}