Total Pageviews

2019/01/08

[Html] [Java] Method of embedding images and other files in webpages as a string of text

Problem
If I would like to embed image in webpage as a string of text (using base64 encoding), how to do it?

How-To
Add two dependencies in your pom.xml
        <dependency>
            <groupId>org.apache.tika</groupId>
            <artifactId>tika-core</artifactId>
            <version>1.18</version>
        </dependency>
  
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>23.0</version>
        </dependency>


Java code (build data uri string):
package demo.util;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.Base64;

import org.apache.tika.Tika;

import com.google.common.io.Files;

public class FileContentCodecUtils {
    
    /**
     * 產生 data uri (https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs).
     * 
     * @param base64str
     *            base 64 string
     * @return data URI 給 img src, 如<img src="data:application/octet-stream;base64,xxxxxxx">
     * @throws IOException
     */
    public static String getDataUri(String base64str) throws IOException {
        Tika tika = new Tika();
        String contentType = tika.detect(new org.apache.commons.codec.binary.Base64InputStream(
                new ByteArrayInputStream(base64str.getBytes("UTF-8"))));

        StringBuilder dataUri = new StringBuilder();
        dataUri.append("data:").append(contentType);
        dataUri.append(";base64,").append(base64str);

        return dataUri.toString();
    }

}


HTML code (assign data URI in img src):
<img src="data:image/png;base64,xxxxxx" /> 



Reference
[1] https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
[2] https://blog.csdn.net/dac55300424/article/details/21093347

No comments: