A note on how to generate a ** data URI ** from a file in Java
** data URI ** is base64 encoded media data etc. and is as follows
data:video/mp4;base64,AAAAIGZ0eXBpc29tAAACAGlzb21pc28y ...==
In HTML
<image src="data:image/png;base64,AAAAIGZ0eXBpc29tAAAC ・ ・ ・">
<video src="data:video/mp4;base64,AAAAIGZ0eXBpc29tAAAC ・ ・ ・">
It is possible to specify src like.
Examine the MIME type of the file.
File file = new File("movie.mp4");
String contentType = Files.probeContentType(file.toPath());
byte[] data = Files.readAllBytes(file.toPath());
--Java 7 approach
String base64str = DatatypeConverter.printBase64Binary(data);
--Java 8 approach
String base64str = Base64.getEncoder().encodeToString(data);
Format as follows
data:[<MIME-type>][;charset=<encoding>][;base64],<data>
StringBuilder sb = new StringBuilder();
sb.append("data:");
sb.append(contentType);
sb.append(";base64,");
sb.append(base64str);
ToDataURI.java
package org.example;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import javax.xml.bind.DatatypeConverter;
public class ToDataURI {
public static void main(String[] args) throws IOException {
//Source file
File file = new File("movie.mp4");
//Examine the content type of a file
String contentType = Files.probeContentType(file.toPath());
//File contents byte[]Load into
byte[] data = Files.readAllBytes(file.toPath());
// byte[]To a base64 string(java7)
String base64str = DatatypeConverter.printBase64Binary(data);
// byte[]To a base64 string(java8)
// String base64str = Base64.getEncoder().encodeToString(data);
//Create a data URI
StringBuilder sb = new StringBuilder();
sb.append("data:");
sb.append(contentType);
sb.append(";base64,");
sb.append(base64str);
//View results
System.out.println(sb.toString());
}
}
data:video/mp4;base64,AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wN ・ ・ ・ Omitted below
Recommended Posts