Introduction
I have on occasion had to convert an image, usually an icon into a data URI to embed in a web application. I was looking for a simple application to perform the conversion, but usually they are included in larger frameworks.
I wrote a quick conversion utility as shown below.
The code can be found in the commons-utils project on GitHub.
Code
package com.example.uri;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Base64;
/**
*
* @author John Yeary <jyeary@bluelotussoftware.com>
*/
public final class Utils {
/**
* Convert a file into base 64 encoded URI.Primarily used for creating
* encoded images to be displayed inline in HTML.
*
* @param file The file to be converted into a data URI.
* @return A base 64 encoded representation of the the file in a data URI
* format.
* @throws IOException If an exception occurs during processing of the file.
*/
public static String toDataURI(final File file) throws IOException {
// Check content type of the file
String contentType = Files.probeContentType(file.toPath());
// Read data as byte[]
byte[] data = Files.readAllBytes(file.toPath());
// Convert byte[] to base64
String encoded = Base64.getEncoder().encodeToString(data);
// Create "data URI"
StringBuilder sb = new StringBuilder();
sb.append("data:");
sb.append(contentType);
sb.append(";base64,");
sb.append(encoded);
return sb.toString();
}
}