Languages
[Edit]
EN

Java - InputStream to Base64 Data URL

7 points
Created by:
Marcin
18520

In this article, we would like to show how to convert InputStream to Base64 Data URL in Java.

Summary:

InputStream inputStream = ...

String mediaType = "image/png";
String dataUrl = Base64Utils.encodeDataUrl(mediaType, inputStream);

// dataUrl :
//   data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAb8...

 

Reusable code example

Main idea of the below solution is:

  • use┬áByteArrayOutputStream to store read data from┬áInputStream,
  • wrap┬áByteArrayOutputStream┬áto Base64 encoded stream,
  • write bytes to Base64┬áencoded┬ástream,
  • extract data from ByteArrayOutputStream as Data URL encoded with┬áBase64.

Image utils:

package com.dirask.examples;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class Base64Utils {

    private static final Base64.Encoder BASE64_ENCODER = Base64.getEncoder();

    private Base64Utils() {
        // nothing here ...
    }

    private static final void writeMetadata(String mediaType, OutputStreamWriter outputWriter) throws IOException {
        outputWriter.write("data:");
        outputWriter.write(mediaType);
        outputWriter.write(";base64,");
        outputWriter.flush();
    }

    private static final void writeContent(InputStream inputStream, OutputStream outputStream) throws IOException {
        byte[] buffer = new byte[1024];
        while (true) {
            int count = inputStream.read(buffer, 0, buffer.length);
            if (count == -1) {
				break;
			}
            outputStream.write(buffer, 0, count);
        }
        outputStream.flush();
    }

    public static final String encodeDataUrl(String mediaType, int inputSize, InputStream inputStream) throws IOException {
        try (ByteArrayOutputStream rawOutputStream = new ByteArrayOutputStream(inputSize);
             OutputStreamWriter utf8OutputWriter = new OutputStreamWriter(rawOutputStream, StandardCharsets.UTF_8);
             OutputStream base64OutputStream = BASE64_ENCODER.wrap(rawOutputStream))
		{
            writeMetadata(mediaType, utf8OutputWriter);
            writeContent(inputStream, base64OutputStream);
            return rawOutputStream.toString();
        }
    }

    public static final String encodeDataUrl(String mediaType, InputStream inputStream) throws IOException {
        return encodeDataUrl(mediaType, 1024, inputStream);
    }
}

Usage example:

package com.dirask.examples;

import java.io.*;

public class Program {

    public static void main(String[] args) throws IOException {

        File imageFile = new File("/path/to/image.png");
        String imageType = "image/png";
        long imageSize = imageFile.length();

        try (FileInputStream imageStream = new FileInputStream(imageFile)) {
            String imageDataUrl = Base64Utils.encodeDataUrl(imageType, (int)imageSize, imageStream);
            System.out.println(imageDataUrl);
        }
    }
}

Example output:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAb8...
Native Advertising
­čÜÇ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé

Join