Skip to content

Commit 59277b4

Browse files
nnhai1991pedja4
authored andcommitted
BAEL-1846: Java Image to Base64 String (eugenp#4600)
* BAEL-1846: Java Image to Base64 String * Move from using main method to Junit test * Update to use environment variables for testing * reformat and add test file
1 parent 234107f commit 59277b4

2 files changed

Lines changed: 43 additions & 0 deletions

File tree

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package com.baeldung.fileToBase64StringConversion;
2+
3+
import static org.junit.Assert.assertTrue;
4+
5+
import java.io.File;
6+
import java.io.IOException;
7+
import java.util.Base64;
8+
9+
import org.apache.commons.io.FileUtils;
10+
import org.junit.Test;
11+
12+
public class FileToBase64StringConversionUnitTest {
13+
14+
private String inputFilePath = "test_image.jpg";
15+
private String outputFilePath = "test_image_copy.jpg";
16+
17+
@Test
18+
public void fileToBase64StringConversion() throws IOException {
19+
//load file from /src/test/resources
20+
ClassLoader classLoader = getClass().getClassLoader();
21+
File inputFile = new File(classLoader
22+
.getResource(inputFilePath)
23+
.getFile());
24+
25+
byte[] fileContent = FileUtils.readFileToByteArray(inputFile);
26+
String encodedString = Base64
27+
.getEncoder()
28+
.encodeToString(fileContent);
29+
30+
//create output file
31+
File outputFile = new File(inputFile
32+
.getParentFile()
33+
.getAbsolutePath() + File.pathSeparator + outputFilePath);
34+
35+
// decode the string and write to file
36+
byte[] decodedBytes = Base64
37+
.getDecoder()
38+
.decode(encodedString);
39+
FileUtils.writeByteArrayToFile(outputFile, decodedBytes);
40+
41+
assertTrue(FileUtils.contentEquals(inputFile, outputFile));
42+
}
43+
}
2.8 KB
Loading

0 commit comments

Comments
 (0)