使用数据URI的Base64编码的OpenType字体面板

12
我希望将一个使用base64编码的OpenType字体作为数据URI添加到font-face中。
目前我已经做到了这一点:
@font-face {
    font-family: 'test';
    src: url(data:font/otf;base64,
        // Base64 string here ...
    ) format('opentype');
}

但我认为它没有正确地将字体包含在我的样式中。如果能提供帮助,我将不胜感激。

请使用 ' 将值括起来。你在使用哪个浏览器? - Praveen Kumar Purushothaman
我试过那个,还有谷歌浏览器。 - user5675649
1
哦,是 font/opentype 而不是 otf - Praveen Kumar Purushothaman
仍然不起作用 :( - user5675649
2个回答

15

虽然没有被问及,但我相信会有人在这里寻找woff2解决方案,并且会遇到和我一样的问题。使用此网站上传文件:https://base64.guru/converter/encode/file 确保使用 "Data URI" 选项。将url()值替换为来自该网站的代码。

对于CSS,我必须使用以下代码:

@font-face {
    font-family: 'MYFONT'; /*This is what your font will be named*/
    src: local('MYFONT'), /* It will check the machine for a font matching this name, if it exists it will use this. Not needed when your are writing the woff2 file since you already sending all the data. */
         url('data:@file/octet-stream;base64,d09GMgABAAAAAK6kABIAAAABgQgAAK47AAA=') /*This is the base64 code copy pasted from the site*/
         format('woff2'); /*This ensures the browser treats it as a WOFF2 file. Notice there is no comma after the url() */
}

为了让你的自定义字体起作用,你需要指定它:
<div style="font-family: MYFONT">
    My new font
</div>

我发布的实际base64代码无法使用。我使用的woff2文件大小为50kb,不希望页面出现大量的base64代码。


1
你使用的是 data:@file 而不是 data:font 吗? - LucasLaurens

10

数据URI始终采用此格式:

data:[<mediatype>][;base64],<data>

每个数据URI的第一部分是媒体类型,在开放式字体中,它是:
font/opentype

那么,您可以像这样使用它:

@font-face{
    font-family: test;
    src: url(data:font/opentype; base64, [base64 string here]);
}

替换
[base64 string here]

使用精确的复制粘贴版本,包括您的base-64编码字符串。

请注意:

  • 您应该使用font/opentype来处理data,而不是otf
  • 您应该复制粘贴完整的base-64编码字符串,不要进行任何更改,比如添加空格等(我相信其中有一些空格)。

在线编码工具

您可以使用this工具,将您的字体文件转换为编码字符串。


“...”有关系吗? - user5675649
只需用您的Base64编码字符串的复制粘贴版本替换“// Base64 string here ...” - Peyman Mohamadpour
所有字体都兼容Base64吗? - user5675649
是的,base64与文件类型无关。它只是一种编码方法,可以读取文件内容并将其编码为字符串。请仔细阅读答案,我相信您会将其应用到实际工作中。 - Peyman Mohamadpour
@Pmpr,如何支持低版本的IE(例如IE8)?因为据我所知,base64只支持IE10及以上版本。如果我错了,请纠正我。 - Krishna Prashatt
你能提供一个示例,让我们复制<style></style>之间的内容吗?(我从其他网站上复制了一些数字,例如这里,但没有成功使其工作) - stevec

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接