Skip to main content
 首页 » 编程设计

图像转换为Base64字符串

2022年07月19日133mengfanrong

图像转换为Base64字符串

本文我们讨论使用Apache Common IO 和 Java 8 自带 Base64 功能把图像文件转为Base64字符串,并反向解码为原图像.

该转换可以应用于任何二进制文件或二进制数组。当我们需要将JSON格式的二进制内容(例如从移动应用程序到REST端点)传输到REST端点时,它非常有用。

maven 依赖

首先我们需要在项目引入依赖,这里示例maven:

<dependency> 
    <groupId>commons-io</groupId> 
    <artifactId>commons-io</artifactId> 
    <version>2.6</version> 
</dependency>

转换图像文件至Base64字符串

首先,我们读文件内容值字节数组,然后使用java8 Base64类编码:

byte[] fileContent = FileUtils.readFileToByteArray(new File(filePath)); 
String encodedString = Base64.getEncoder().encodeToString(fileContent);

encodedString是a- za -z0-9+/集合中的字符串,解码器不会解析集合之外的任何字符。

转换Base64字符串至图像文件

现在我们把Base64字符串解码至二进制内容并写至新的图像文件:

byte[] decodedBytes = Base64.getDecoder().decode(encodedString); 
FileUtils.writeByteArrayToFile(new File(outputFileName), decodedBytes);

测试代码

最后写单元测试验证代码是否正常工作,我们验证读取文件编码为Base64字符串,然后解密至新的文件:

public class FileToBase64StringConversionUnitTest {
    
 
    private String inputFilePath = "test_image.jpg"; 
    private String outputFilePath = "test_image_copy.jpg"; 
 
    @Test 
    public void fileToBase64StringConversion() throws IOException { 
        // load file from /src/test/resources 
        ClassLoader classLoader = getClass().getClassLoader(); 
        File inputFile = new File(classLoader 
          .getResource(inputFilePath) 
          .getFile()); 
 
        byte[] fileContent = FileUtils.readFileToByteArray(inputFile); 
        String encodedString = Base64 
          .getEncoder() 
          .encodeToString(fileContent); 
 
        // create output file 
        File outputFile = new File(inputFile 
          .getParentFile() 
          .getAbsolutePath() + File.pathSeparator + outputFilePath); 
 
        // decode the string and write to file 
        byte[] decodedBytes = Base64 
          .getDecoder() 
          .decode(encodedString); 
        FileUtils.writeByteArrayToFile(outputFile, decodedBytes); 
 
        assertTrue(FileUtils.contentEquals(inputFile, outputFile)); 
    } 
}

总结

本文详细介绍了将任何文件的内容编码为Base64字符串、将Base64字符串解码为字节数组并使用Apache Common IO 和 Java 8 基本特性将其保存到文件中。


本文参考链接:https://blog.csdn.net/neweastsun/article/details/82226907
阅读延展