dan*_*132 7 .net fonts gdi+ privatefontcollection windows-server-2012-r2
我有一个.NET 3.5应用程序,使用PrivateFontCollection.AddMemoryFont将字体加载到内存中,并使用它们生成图像.我最近在Windows Server 2012 R2上安装了它,它产生间歇性错误.
这个方法说明了这个问题:
private Bitmap getImage(byte[] fontFile)
{
using (PrivateFontCollection fontCollection = new PrivateFontCollection())
{
IntPtr fontBuffer = Marshal.AllocCoTaskMem(fontFile.Length);
Marshal.Copy(fontFile, 0, fontBuffer, fontFile.Length);
fontCollection.AddMemoryFont(fontBuffer, fontFile.Length);
Bitmap image = new Bitmap(200, 50);
using (Font font = new Font(fontCollection.Families[0], 11f, FontStyle.Regular))
{
using (Graphics graphics = Graphics.FromImage(image))
{
graphics.DrawString(String.Format("{0:HH:mm:ss}", DateTime.Now), font, Brushes.White, new PointF(0f, 0f));
}
}
return image;
}
}
Run Code Online (Sandbox Code Playgroud)
在Windows 7上,这一切都是一致的.在Windows Server 2012 R2上,如果使用多种字体重复调用,则会失败.例如:
getImage(File.ReadAllBytes("c:\\Windows\\Fonts\\Arial.ttf"));
Run Code Online (Sandbox Code Playgroud)
即使被调用数百次,但使用多种字体调用,它仍可正常工作:
getImage(File.ReadAllBytes("c:\\Windows\\Fonts\\Wingding.ttf"));
getImage(File.ReadAllBytes("c:\\Windows\\Fonts\\Arial.ttf"));
Run Code Online (Sandbox Code Playgroud)
将适用于前几次调用(20左右),但随后将开始产生随机结果(第二次调用有时会返回带有文本的图像 - 即它正在混合字体).
我偶尔(很少)在DrawString调用中得到"GDI +中发生了一般错误".
Windows 7上不会发生这些错误.
我已经尝试了各种选项来清理而没有任何成功.
作为一种解决方法,我尝试将字体文件写入磁盘,然后使用AddFontFile加载,但是(在Windows 2012 R2上)字体文件在进程的生命周期内被锁定,因此无法删除.这使得此选项无法接受.
任何帮助让AddMemoryFont一致地工作,或者让AddFontFile解锁文件,将非常感激.
一个迟到的答案,但也许其他人会对此感到满意:我遇到了完全相同的问题,经过数小时的尝试和错误,我发现对我来说一个可行的解决方案是将字体(数据库中的字节数组)保存到本地文件,然后使用 addFontFile 方法加载文件。
所有的问题都消失了。这不是一个理想的解决方案,但却是一个可行的解决方案。
var path = Path.Combine(TemporaryFontPath, customFont.FontFileName);
if (!Directory.Exists(Path.GetDirectoryName(path)))
Directory.CreateDirectory(Path.GetDirectoryName(path));
if(!File.Exists(path))
File.WriteAllBytes(path, customFont.FontBytes);
using (var pvc = new PrivateFontCollection())
{
pvc.AddFontFile(path);
return pvc.Families.FirstOrDefault();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1276 次 |
| 最近记录: |