数据 URI - 如何在 Java 中创建它们?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14996746/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 18:08:20  来源:igfitidea点击:

Data URI - how to create them in Java?

javaimagedata-uri

提问by Khizar

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?

我刚刚被告知使用数据 URI 发送图像的缩略图。我一直在搜索它,但我发现它基本上是一个文件的文本表示,可以直接在 HTML 中使用。我真的找不到如何在 Java 中创建数据 URI。我有一个文件的输入流。有人可以对此有所了解并指出一种方法来生成它吗?

回答by Andrew Thompson

E.G. for an image:

图像的 EG:

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

Example

例子

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

运行下面的代码。如果 FF 是默认浏览器,您可能会看到如下内容:

Data URI image in FF

FF 中的数据 URI 图像

import java.awt.*;
import java.awt.image.BufferedImage;
import javax.xml.bind.DatatypeConverter;
import javax.imageio.ImageIO;
import java.io.ByteArrayOutputStream;
import java.io.*;

public class DataUriConverter {

    public static void main(String[] args) throws Exception {
        int sz = 200;
        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(Color.BLUE);
        for (int ii = 0; ii < sz; ii += 5) {
            g.drawOval(ii, ii, sz - ii, sz - ii);
        }
        g.dispose();

        // convert the image
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, "png", baos);
        System.out.println("baos.toByteArray() " + baos.toByteArray());
        System.out.println("baos.toByteArray().length " + baos.toByteArray().length);
        String data = DatatypeConverter.printBase64Binary(baos.toByteArray());
        String imageString = "data:image/png;base64," + data;
        String html =
                "<html><body><img src='" + imageString + "'></body></html>";

        // 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);
    }
}

回答by riversun

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
  1. 检查文件内容类型
  2. 将文件数据读入字节[]
  3. 将 byte[] 数据转换为 base64
  4. 创建“数据URI”格式

You can get like

你可以像

data:video/mp4;base64,AAAAIGZ0eXBpc29tAAACAGlzb21p....