Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data URI - how to create them in Java?

I have just been told to send the thumbnail of an image using data URI. I have been searching it but all I found was that its basically a textual representation of a file and can be directly used in HTML. I could not really find how to make a data URI in Java. I have an input stream of a file. Can someone please shed some light on it and point me to a way to generate this?

like image 461
Khizar Avatar asked Feb 21 '13 07:02

Khizar


People also ask

How to define URI in Java?

A URI is a uniform resource identifier while a URL is a uniform resource locator. Hence every URL is a URI, abstractly speaking, but not every URI is a URL.

What is URI datatype?

A Uniform Resource Identifier (URI) is a character sequence that identifies a logical (abstract) or physical resource -- usually, but not always, connected to the internet. A URI distinguishes one resource from another.

How do you use data URI?

A data URI is a base64 encoded string that represents a file. Getting the contents of a file as a string means that you can directly embed the data within your HTML or CSS code. When the browser encounters a data URI in your code, it's able to decode the data and construct the original file.

Does Java have a URI class?

net. URI class in Java. This class provides methods for creating URI instances from its components or by parsing the string form of those components, for accessing and retrieving different components of a URI instance.


2 Answers

E.G. for an image:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
    ImageIO.write(image, "png", baos);
} catch (IOException e) {
    e.printStackTrace();
}
String imageString = "data:image/png;base64," +
    Base64.getEncoder().encodeToString(bytes);

Example

Run the code below. If FF is the default browser, you might see something like this:

Data URI image in FF

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import java.util.Base64;

public class DataUriConverter {

    static String getImageAsString(BufferedImage image) throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // serialize the image
        ImageIO.write(image, "png", baos);
        // convert the written image to a byte[]
        byte[] bytes = baos.toByteArray();
        System.out.println("bytes.length " + bytes.length);
        // THIS IS IT! Change the bytes to Base 64 Binary
        String data = Base64.getEncoder().encodeToString(bytes);
        // add the 'data URI prefix' before returning the image as string
        return "data:image/png;base64," + data;
    }

    static BufferedImage getImage() {
        int sz = 500;
        BufferedImage image = new BufferedImage(
                sz, sz, BufferedImage.TYPE_INT_ARGB);

        // paint the image..
        Graphics2D g = image.createGraphics();
        g.setRenderingHint(
                RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        g.setColor(new Color(0,0,255,63));
        g.setStroke(new BasicStroke(1.5f));
        for (int ii = 0; ii < sz; ii += 5) {
            g.drawOval(ii, ii, sz - ii, sz - ii);
        }
        g.dispose();

        return image;
    }

    public static void main(String[] args) throws Exception {
        String imageString = getImageAsString(getImage());
        String htmlFrag = "<html><body><img src='%1s'></body></html>";
        String html = String.format(htmlFrag, imageString);

        // write the HTML
        File f = new File("image.html");
        FileWriter fw = new FileWriter(f);
        fw.write(html);
        fw.flush();
        fw.close();

        // display the HTML
        Desktop.getDesktop().open(f);
    }
}
like image 62
Andrew Thompson Avatar answered Oct 27 '22 16:10

Andrew Thompson


Here is my 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");

        // check content type of the file
        String contentType = Files.probeContentType(file.toPath());

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

        // convert byte[] to base64(java7)
        String base64str = DatatypeConverter.printBase64Binary(data);

        // convert byte[] to base64(java8)
        // String base64str = Base64.getEncoder().encodeToString(data);

        // cretate "data URI"
        StringBuilder sb = new StringBuilder();
        sb.append("data:");
        sb.append(contentType);
        sb.append(";base64,");
        sb.append(base64str);

        System.out.println(sb.toString());

    }
}

Processing flow

  1. Check file contentType
  2. Read file data into byte[]
  3. Convert byte[] data to base64
  4. Create "data URI" format

You can get like

data:video/mp4;base64,AAAAIGZ0eXBpc29tAAACAGlzb21p....
like image 2
riversun Avatar answered Oct 27 '22 16:10

riversun