【翻译】图像到Base64字符串转换

本文教程介绍了如何使用Apache Commons IO和Java 8的Base64类将图片文件转换为Base64字符串,以及如何将Base64字符串还原为图片。此过程在需要通过JSON传输二进制内容时特别有用,例如在移动应用到REST服务的数据交换中。

1 概览

在这个简短的教程中,我们将介绍如何使用 Apache Common IO 包和 Java 8 原生类 Base64 将图片文件转成 base64 字符串,然后把 base64 字符串再转成图片。

这个操作也可以应用到任何二进制文件或者二进制数组中。当我们需要以 json 格式传输二进制内容的时候,例如从移动app程序传到到 REST 端时,它非常有用。

2 Maven 依赖

添加一下依赖到 pom.xml 中:

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

你可以在 maven 中央仓库找到 commons-io 包的最新版本。Maven Central.

3 将图片转成 base64 字符串

首先,我们将文件内容转成 byte 数组,然后使用 Java 8 的 Base64 类编码这个数组。

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

encodeToString 字段是 A-Za-z0-9+/ 集合中的字符串,解码器拒绝该集合之外的任何字符。

4 将 base64 字符串转成图片

现在我们有一个 Base64 字符串了,让我们把它编码回去成二进制文件并且写入文件。

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

5 测试我们的代码

最后,我们可以通过读取一个文件,将其编码为 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));
    }
}

6 结论

这篇文章非常切题,它介绍了将任何文件的内容编码为 Base64 字符串,并将Base64 字符串解码为字节数组,并使用 Apache Common IO 和 Java 8 特性将其保存到文件中。

原文地址:https://www.baeldung.com/java-base64-image-string

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

伍六七AI编程

你猜你给我1分我要不要

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值