目录
1.导入依赖
使用到工具类依赖
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
2、视频转Base64
2.1 视频转Base64输出txt文本
通过FileUtils.openInputStream()
将视频文件转化成输入流。
然后通过IOUtils.toByteArray()
直接将流经过Base64编码为String。最后通过FileWriter
直接将String写入即可。
@Test
public void test() throws IOException {
String sourceVideo = "/Users/LiuShihao/IdeaProjects/as-video-call-bussiness/as-video-business/src/main/resources/static/5.3gp" ;
InputStream inputStream = FileUtils.openInputStream(new File(sourceVideo));
// encode
String ss = new String(Base64.getEncoder().encode(IOUtils.toByteArray(inputStream)), Charsets.ISO_8859_1);
File txtFilePath = new File("/Users/LiuShihao/IdeaProjects/as-video-call-bussiness/as-video-business/src/main/resources/static/5.3.txt");
FileWriter fileWriter = new FileWriter(txtFilePath);
fileWriter.write(ss);
fileWriter.flush();
fileWriter.close();
}
2.2 Base64转视频
使用BufferReader
直接读取txt信息。一行行的读取到一个StringBuffer中,转成String,在经过Base64解码。最后通过字节流写成一个新的mp4文件。
@Test
public void test2() throws IOException {
File txtFilePath = new File("/Users/LiuShihao/IdeaProjects/as-video-call-bussiness/as-video-business/src/main/resources/static/1.3.txt");
BufferedReader bufferedReader = new BufferedReader(new FileReader(txtFilePath));
StringBuffer sbf = new StringBuffer();
String tempStr;
while ((tempStr = bufferedReader.readLine()) != null) {
sbf.append(tempStr);
}
bufferedReader.close();
String ss = sbf.toString();
InputStream is = new ByteArrayInputStream(Base64.getDecoder().decode(ss.getBytes(Charsets.ISO_8859_1)));
FileOutputStream fos = new FileOutputStream(new File("/Users/LiuShihao/IdeaProjects/as-video-call-bussiness/as-video-business/src/main/resources/static/1.3gp_copy.mp4"));
byte[] bytes = new byte[is.available()];
System.out.println(bytes.length);
int x = -1;
while((x = is.read(bytes)) != -1) {
fos.write(bytes);
}
is.close();
fos.close();
}
3、图片转Base64
3.1 图片转Base64
//获取图片
InputStream inputStream = null;
//url是图片路径
inputStream = FileUtils.openInputStream(new File(url));
String base64 = null;
base64 = new String(Base64.getEncoder().encode(IOUtils.toByteArray(inputStream)), Charsets.UTF_8);
3.2 Base64转图片
public ResponseData base64ToImage(@RequestBody Map<String,String> map ){
ResponseData<Object> data = ResponseData.defaultSuccess();
try {
String base64 = map.get("base64");
ByteArrayInputStream in = new ByteArrayInputStream(Base64.getDecoder().decode(base64.getBytes(Charsets.UTF_8)));
File file = new File("/Users/LiuShihao/IdeaProjects/besttone-call-business/1.jpeg");
FileOutputStream fos = new FileOutputStream(file);
byte[] bytes = new byte[in.available()];
int x = -1;
while((x = in.read(bytes)) != -1) {
fos.write(bytes);
}
in.close();
fos.close();
data.setData("SUCCESS");
}catch (Exception e){
data = ResponseData.defaultFail();
data.setMessage(e.getMessage());
}
return data;
}