Generates a front-readable Data URI
from the bytes obtained from the image file.
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}"
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.
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.
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