(教程)如何在 SVG 中嵌入 base64 图像

创建 SVG 文件时,您可以通过多种方式嵌入图像,包括本地图像、外部 URL 和使用 base64 图像。本教程介绍如何嵌入 base64 图像以及为什么要这样做。

为什么要将图像嵌入为 base64?

将图像嵌入为 base64 内容将减少所需的请求数,因为图像现在是 SVG 文件的一部分。但是,base64 内容将比图像大 20-25%。所以这种方法对中小型图像有益,但大型图像对性能的影响要大得多。

如何在 SVG 中嵌入 base64 图像

    •    将图像转换为 base64 字符串(此处显示 Java 代码)

    •    创建一个具有空 src 值的 img 标签

    •    在 src 属性中构造数据 URI

    1    添加数据媒体类型以匹配原始图像

    2    添加与编码中使用的字符集匹配的字符集

    3    添加您之前创建的 base64 数据

以下是将 base64 图像嵌入 SVG 的代码……

final ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
//Can be any support image format
final String formatName = "jpg";

//Convert image data to Base64 and write date to the output stream
final BufferedImage image = ImageIO.read(new File("/path/to/file"));
ImageIO.write(image, formatName, Base64.getEncoder().wrap(os));

//Create Base64 string
final String base64 = os.toString(StandardCharsets.UTF_8.name());

} catch (final IOException ioe) {
throw new UncheckedIOException(ioe);
}
<image href="" alt="Description of the image" />
<image href="data:image/jpeg;" alt="Description of the image" />
<image href="data:image/jpeg;charset=utf-8;" alt="Description of the image" />
<image href="data:image/jpeg;charset=utf-8;base64,<DATA>" alt="Description of the image" />

 

我们的主页:PDF 转 HTML5、Java 图像库、Java PDF SDK - IDRsolutions

我们的公众号:IDRSolutions

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值