一、使用到的依赖
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.10</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
</dependency>
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;
import org.junit.Test;
import org.springframework.util.Base64Utils;
import org.springframework.util.ResourceUtils;
import java.io.*;
二、将图片转换为base64
使用spring boot自带的ResourceUtils从资源路径中获取文件,通过IO转换为字节、再将字节转换为Base64
//将图片转换为base64
public static String jpgToBase() throws IOException {
//使用spring boot自带的ResourceUtils从资源路径中获取文件
File file = ResourceUtils.getFile("F:\\桌面壁纸\\2.jpg");
FileInputStream fileInputStream = new FileInputStream(file);
//使用IO流将其转换为字节数组
byte[] bytes = IOUtils.toByteArray(fileInputStream);
//将字节转换为base64
String encodeBase64 = Base64.encodeBase64String(bytes);
//关闭IO流
fileInputStream.close();
return encodeBase64;
}
二、base64转换为图片
@Test
public void base64ToImage() {
try {
//获取Base64,并解码成字节
byte[] bytes = Base64Utils.decodeFromString(jpgToBase());
//新图片的文件路径
File file = new File("F:\\桌面壁纸\\test2.jpg");
//判断文件所在目录是否存在,如果不存在,则就创建目录
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
//创建新的图片文件
file.createNewFile();
//创建文件输出流
FileOutputStream fos = new FileOutputStream(file);
//将字节写入到图片文件中
fos.write(bytes);
fos.close();
System.out.println(true);
} catch (IOException e) {
e.printStackTrace();
System.out.println(false);
}
}
需要注意的是,由于Base64编码字符串比原始图片文件更大,因此在使用Base64编码字符串传输图片时,需要考虑网络传输的带宽和速度等因素。