How to Convert InputStream to Base64 String – 如何将InputStream转换为Base64字符串

最后修改: 2022年 6月 30日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

Base64 is a text encoding scheme that provides portability for binary data between applications and platforms. Base64 can be used to store binary data in a database string column, thereby avoiding messy file operations. When combined with the data URI scheme, Base64 can be used to embed images in web pages and emails, in conformance with the HTML and Multipurpose Internet Mail Extensions (MIME) standards.

Base64是一种文本编码方案,为应用程序和平台之间的二进制数据提供可移植性。Base64可用于将二进制数据存储在数据库的字符串列中,从而避免了混乱的文件操作。当与数据URI方案结合使用时,Base64可用于在网页和电子邮件中嵌入图像,符合HTML和多用途互联网邮件扩展(MIME)标准。

In this brief tutorial, we’ll demonstrate Java Streaming IO functions and the built-in Java Base64 class to load binary data as an InputStream and then convert it to a String.

在这个简短的教程中,我们将演示Java Streaming IO函数和内置的Java Base64类,以加载二进制数据作为InputStream,然后将其转换成String

2. Setup

2.设置

Let’s look at the dependencies and the test data we’ll need for the code.

让我们看一下代码的依赖性和我们需要的测试数据。

2.1. Dependencies

2.1. 依赖性

We’ll use the Apache IOUtils library for convenient access to testing data files by adding its dependency to our pom.xml:

我们将使用Apache IOUtils库,通过将其依赖性添加到我们的pom.xml中,以方便访问测试数据文件。

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

2.2. Test Data

2.2 测试数据

A binary test data file is needed here. So we’ll add a logo.png image file to our standard src/test/resources folder.

这里需要一个二进制的测试数据文件。所以我们要在我们的标准src/test/resources文件夹中添加一个logo.png图像文件。

3. Converting InputStream to Base64 String

3.将InputStream转换为Base64字符串

Java has built-in support for Base64 encoding and decoding in the java.util.Base64 class. So we’ll be using the static methods from there to do the heavy lifting. 

Java在java.util.Base64类中内置了对Base64编码和解码的支持。所以我们将使用那里的静态方法来完成繁重的工作。

Base64.encode() method expects a byte array, and our image is in a file. Therefore, we need to first convert the file to an InputStream and then read the stream, byte-by-byte, into an array.

Base64.encode()方法期望一个字节数组,而我们的图像是在一个文件中。因此,我们需要首先将文件转换为InputStream,然后将该流逐个读入一个数组。

We’re using the IOUtils.toByteArray() method from the Apache commons-io package as a convenient alternative to the otherwise verbose Java-only approach.

我们使用Apache commons-io包中的IOUtils.toByteArray()方法,以方便替代只用Java的繁琐方法。

First, we’ll write a simple method to generate a ‘poor man’s’ checksum:

首先,我们将写一个简单的方法来生成一个 “穷人 “的校验和。

int calculateChecksum(byte[] bytes) {
    int checksum = 0; 
    for (int index = 0; index < bytes.length; index++) {
        checksum += bytes[index]; 
    }
    return checksum; 
}

We’ll use it to compare the two arrays, verifying that they match.

我们将用它来比较这两个数组,验证它们是否匹配。

The next lines open the file, convert it to a byte array, and then Base64 encode it to a String:

接下来的几行打开文件,将其转换为字节数组,然后将其Base64编码为String

InputStream sourceStream  = getClass().getClassLoader().getResourceAsStream("logo.png");
byte[] sourceBytes = IOUtils.toByteArray(sourceStream);

String encodedString = Base64.getEncoder().encodeToString(sourceBytes); 
assertNotNull(encodedString);

The String looks like a block of random characters. In fact, it is not random, as we see in the verification steps:

该字符串看起来像一个随机字符块。事实上,它不是随机的,正如我们在验证步骤中看到的那样。

byte[] decodedBytes = Base64.getDecoder().decode(encodedString);
assertNotNull(decodedBytes);
assertTrue(decodedBytes.length == sourceBytes.length);
assertTrue(calculateChecksum(decodedBytes) == calculateChecksum(sourceBytes));

4. Conclusion

4.总结

In this article, we’ve demonstrated the encoding of a InputStream to a Base64 string and the successful decoding of that string back into a binary array.

在这篇文章中,我们演示了将InputStream编码为Base64字符串,并将该字符串成功解码为二进制数组。

As always, the code presented in this article is available over on GitHub.

一如既往,本文介绍的代码可在GitHub上获得over。