gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 19:42:21 25 4
gpt4 key购买 nike

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

最佳答案

例如对于图像:

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 是默认浏览器,您可能会看到如下内容:

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

关于java - 数据 URI - 如何在 Java 中创建它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14996746/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com