How to create a data URI (base64) in Java

A note on how to generate a ** data URI ** from a file in Java

What is a data URI?

** 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.

1. Check the MIME type that represents the file type

Examine the MIME type of the file.

File file = new File("movie.mp4");

String contentType = Files.probeContentType(file.toPath());

2. Read all the contents of the file into the byte [] array

byte[] data = Files.readAllBytes(file.toPath());

3. Encode the byte [] array to base64

--Java 7 approach

 String base64str = DatatypeConverter.printBase64Binary(data);

--Java 8 approach

 String base64str = Base64.getEncoder().encodeToString(data);

4. Make data URI format

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);

Full source code

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());

	}
}

When executed, the data URI is completed

data:video/mp4;base64,AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wN ・ ・ ・ Omitted below

Recommended Posts

How to create a data URI (base64) in Java
How to create a Java environment in just 3 seconds
[Java] How to create a folder
How to do base conversion in Java
How to create a new Gradle + Java + Jar project in Intellij 2016.03
How to display a web page in Java
How to create a theme in Liferay 7 / DXP
How to easily create a pull-down in Rails
How to create a method
How to clear all data in a particular table
I tried to create a Clova skill in Java
How to store Rakuten API data in a table
How to convert A to a and a to A using AND and OR in Java
How to convert a file to a byte array in Java
How to make a Java container
How to learn JAVA in 7 days
How to use classes in Java?
How to name variables in Java
How to make a Java array
How to concatenate strings in java
How to use JSON data in WebSocket communication (Java, JavaScript)
How to create a lightweight container image for Java apps
How to create a placeholder part to use in the IN clause
How to store a string from ArrayList to String in Java (Personal)
Create a method to return the tax rate in Java
How to develop and register a Sota app in Java
How to simulate uploading a post-object form to OSS in Java
How to create a service builder portlet in Liferay 7 / DXP
How to make a Java calendar Summary
How to implement date calculation in Java
How to implement Kalman filter in Java
Multilingual Locale in Java How to use Locale
How to get date data in Ruby
Create variable length binary data in Java
How to insert a video in Rails
How to implement a job that uses Java API in JobScheduler
[Introduction to Java] How to write a Java program
How to create a Maven repository for 2020
How to automatically operate a screen created in Java on Windows
How to make a Discord bot (Java)
Create a TODO app in Java 7 Create Header
How to implement coding conventions in Java
How to embed Janus Graph in Java
How to print a Java Word document
How to get the date in java
[Swift5] How to create a splash screen
[rails] How to create a partial template
How to publish a library in jCenter
How to overwrite Firebase data in Swift
How to test a private method in Java and partially mock that method
How to create a query using variables in GraphQL [Using Ruby on Rails]
[Personal memo] How to interact with a random number generator in Java
To create a Zip file while grouping database search results in Java
[Java] How to receive numerical data separated by spaces in standard input
How to pass a proxy when throwing REST over SSL in Java
How to get the absolute path of a directory running in Java
[Java] [For beginners] How to insert elements directly in a 2D array
How to create your own annotation in Java and get the value
How to create a database for H2 Database anywhere
Two ways to start a thread in Java + @
Create a CSR with extended information in Java