如何通过URL获取字体并在PHP中转换为Base64(Data Uri)?
PHP代码:
function getDataURI($fontUrl, $mime = '') {
$content = get_web_page($fontUrl);
$content = $content['content'];
return 'data: '.(function_exists('mime_content_type') ? mime_content_type($fontUrl) : $mime).';base64,'.base64_encode($content);
}
结果:
@font-face {
font-family: 'LinotypeUniversW01-Ligh 723625';
src: url('data:font/opentype;base64,PCFET0NUWVBFIGh0bWwgUFVCTElDICItLy9XM0MvL0RURCBIVE1MIDQuMDEvL0VOIiAiaHR0cDovL3d3dy53My5vcmcvVFIvaHRtbDQvc3RyaWN0LmR0ZCI+IDxodG1sPjxoZWFkPiA8bWV0YSBodHRwLWVxdWl2PSJDb250ZW50LVR5cGUiIGNvbnRlbnQ9InRleHQvaHRtbDsgY2hhcnNldD11dGYtOCI+IDx0aXRsZT5FUlJPUjogVGhlIHJlcXVlc3RlZCBVUkwgY291bGQgbm90IGJlIHJldHJpZXZlZDwvdGl0bGU+IDxzdHlsZSB0eXBlPSJ0ZXh0L2NzcyI+PCEtLSAgICVsICBib2R5IDpsYW5nKGZhKSB7IGRpcmVjdGlvbjogcnRsOyBmb250LXNpemU6IDEwMCU7IGZvbnQtZmFtaWx5OiBUYWhvbWEsIFJveWEsIHNhbnMtc2VyaWY7IGZsb2F0OiByaWdodDsgfSA6bGFuZyhoZSkgeyBkaXJlY3Rpb246IHJ0bDsgZmxvYXQ6IHJpZ2h0OyB9ICAtLT48L3N0eWxlPiA8L2hlYWQ+PGJvZHk+IDxkaXYgaWQ9InRpdGxlcyI+IDxoMT5FUlJPUjwvaDE+IDxoMj5UaGUgcmVxdWVzdGVkIFVSTCBjb3VsZCBub3QgYmUgcmV0cmlldmVkPC9oMj4gPC9kaXY+IDxocj4gIDxkaXYgaWQ9ImNvbnRlbnQiPiA8cD5UaGUgZm9sbG93aW5nIGVycm9yIHdhcyBlbmNvdW50ZXJlZCB3aGlsZSB0cnlpbmcgdG8gcmV0cmlldmUgdGhlIFVSTDogPGEgaHJlZj0iaHR0cD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,一切正常。
感谢您的帮助。
答案 0 :(得分:0)
好的,我找到了答案:
http://snipplr.com/view.php?codeview&id=70078
/**
* Data URI base64 PHP function.
*
* @author Pierre-Henry Soria <ph7software@gmail.com>
* @copyright (c) 2012-2013, Pierre-Henry Soria. All Rights Reserved.
* @license Lesser General Public License (LGPL) <http://www.gnu.org/copyleft/lesser.html>
* @param string $sFile The path of your file to encode.
* @return string The encoded data in base64.
*/
function base64DataUri($sFile)
{
// Switch to right MIME-type
$sExt = strtolower(substr(strrchr($sFile, '.'), 1));
switch($sExt)
{
case 'gif':
case 'jpg':
case 'png':
$sMimeType = 'image/'. $sExt;
break;
case 'ico':
$sMimeType = 'image/x-icon';
break;
case 'eot':
$sMimeType = 'application/vnd.ms-fontobject';
break;
case 'otf':
case 'ttf':
case 'woff':
$sMimeType = 'application/octet-stream';
break;
default:
exit('Invalid extension file!');
}
$sBase64 = base64_encode(file_get_contents($sFile));
return "data:$sMimeType;base64,$sBase64";
}