[Java] Generate Data URI from byte string of file contents [Kotlin]

things to do

Generates a front-readable Data URI from the bytes obtained from the image file.

manner

The sample code is as follows.

import java.util.Base64

val bytes: ByteArray = //Byte sequence obtained from the file
val base64Bytes: ByteArray = Base64.getEncoder().encode(bytes) //Base64 encoding
val base64Utf8String = String(base64Bytes, Charsets.UTF_8) // UTF-Conversion to 8

val mimeType: String = //MIME Type obtained by some method

//Data URI generation
val dataUri: String = "data:${mimeType};base64,${base64Utf8String}"

Commentary

Encoding to Base64

Encoding to Base64 can be done without installing a library by using the encoder defined in java.util.Base64 in Java8 or later.

Three types of encoders, basic, ʻURL, and MIME`, are defined here, but as shown in the sample, they cannot be properly interpreted at the front without using the basic encoder.

Conversion to string

Since the encoded result is a byte string, it cannot be treated as a Data URI unless it is properly converted to a character string.

Get MIME Type

The sample code does not describe how to get the MIME Type, but unless you have a specific consideration, you should guess from the extension.

It is also possible to strictly determine the MIME Type by using ʻApache Tika`.

Recommended Posts

[Java] Generate Data URI from byte string of file contents [Kotlin]
[Java] Get MimeType from the contents of the file with Apathce Tika [Kotlin]
Generate source code from JAR file with JD-GUI of Java Decompiler project
JAVA: jar, aar, view the contents of the file
Java language from the perspective of Kotlin and C #
[Java] Get Charset with Apathce Tika / Initialize String from Charset [Kotlin]
[Java] How to convert a character string from String type to byte type
Generate Stream from an array of primitive types in Java
How to check for the contents of a java fixed-length string
[Java] Speed comparison of string concatenation
Various methods of Java String class
Replace the contents of the Jar file
Generate HashMap from XML resource file
Run a batch file from Java
[Java] Runtime Data Areas of JVM
Generics of Kotlin for Java developers
[Java] Correct comparison of String type