【问题标题】:Data URI - how to create them in Java?数据 URI - 如何在 Java 中创建它们?
【发布时间】:2013-02-06 10:50:12
【问题描述】:

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

【问题讨论】:

    标签: java image data-uri


    【解决方案1】:

    例如对于图像:

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

    示例

    运行下面的代码。如果 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);
        }
    }
    

    【讨论】:

    • 虽然这似乎是正确的,但我会评论说,对 DatatypeConverter 的调用将在较新版本的 Java 中失败。替换为Base64.getEncoder().encodeToString 以遵守。
    • 没错,@matsa!感谢您的提醒。我已编辑答案以使用 Base64 类。
    【解决方案2】:

    这是我的例子。

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

    处理流程

    1. 检查文件内容类型
    2. 将文件数据读入byte[]
    3. 将 byte[] 数据转换为 base64
    4. 创建“数据 URI”格式

    你可以喜欢

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-19
      • 2015-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-11
      • 1970-01-01
      相关资源
      最近更新 更多