如何从 Base64String 反序列化上传的字体?
How to deserialize an uploaded font from a Base64String?
我需要从上传的字体中获取字体系列名称。用户上传 .ttf 文件。当我尝试反序列化数据时,出现以下错误 "The input stream is not a valid binary format." 字体数据是通过 HTML5 FileReader 使用 readAsDataURL() 上传的。
谁能发现我做错了什么?我怀疑我使用了错误的解串器...但我不确定。
//clean the font data of encoding
var cleanFontData = brandingsFontAddViewModel.FontData.Split(',')[1];
var fontBytes = Convert.FromBase64String(cleanFontData);
using (Stream memStream = new MemoryStream(fontBytes, 0, fontBytes.Length))
{
var deserializer = new BinaryFormatter();
var font = (Font)deserializer.Deserialize(memStream);
}
终于找到答案了。
// used to store our font and make it available in our app
var pfc = new PrivateFontCollection();
IntPtr data = Marshal.AllocCoTaskMem((int) ms.Length);
Marshal.Copy(fontBytes, 0, data, (int)ms.Length);
pfc.AddMemoryFont(data, (int)ms.Length);
Marshal.FreeCoTaskMem(data);
var fontWithMime = "data:application/x-font-truetype;charset=utf-8;base64," + cleanFontData;
fontName = pfc.Families[0].Name;
我需要从上传的字体中获取字体系列名称。用户上传 .ttf 文件。当我尝试反序列化数据时,出现以下错误 "The input stream is not a valid binary format." 字体数据是通过 HTML5 FileReader 使用 readAsDataURL() 上传的。
谁能发现我做错了什么?我怀疑我使用了错误的解串器...但我不确定。
//clean the font data of encoding
var cleanFontData = brandingsFontAddViewModel.FontData.Split(',')[1];
var fontBytes = Convert.FromBase64String(cleanFontData);
using (Stream memStream = new MemoryStream(fontBytes, 0, fontBytes.Length))
{
var deserializer = new BinaryFormatter();
var font = (Font)deserializer.Deserialize(memStream);
}
终于找到答案了。
// used to store our font and make it available in our app
var pfc = new PrivateFontCollection();
IntPtr data = Marshal.AllocCoTaskMem((int) ms.Length);
Marshal.Copy(fontBytes, 0, data, (int)ms.Length);
pfc.AddMemoryFont(data, (int)ms.Length);
Marshal.FreeCoTaskMem(data);
var fontWithMime = "data:application/x-font-truetype;charset=utf-8;base64," + cleanFontData;
fontName = pfc.Families[0].Name;