BAEL-1846: Java Image to Base64 String (#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
This commit is contained in:
Hai Nguyen 2018-07-06 03:20:07 +08:00 committed by Predrag Maric
parent 234107f519
commit 59277b4339
2 changed files with 43 additions and 0 deletions

View File

@ -0,0 +1,43 @@
package com.baeldung.fileToBase64StringConversion;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.util.Base64;
import org.apache.commons.io.FileUtils;
import org.junit.Test;
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));
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB