I have a .NET 3.5 application that loads fonts into memory using PrivateFontCollection.AddMemoryFont and uses them to create images. I recently installed this on Windows Server 2012 R2 and it produces intermittent errors.
The problem is illustrated by this method:
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; } }
On Windows 7, this works in sequence. In Windows Server 2012 R2, it fails if called multiple times using more than one font. For instance:
getImage(File.ReadAllBytes("c:\\Windows\\Fonts\\Arial.ttf"));
works even when called hundreds of times, but calls more than one font:
getImage(File.ReadAllBytes("c:\\Windows\\Fonts\\Wingding.ttf")); getImage(File.ReadAllBytes("c:\\Windows\\Fonts\\Arial.ttf"));
will work for the first few calls (about 20 or so), but then it will start to generate random results (the second call sometimes returns an image with text in the wings, that is, it mixes fonts).
I also sometimes (rarely) get a βCommon error that occurred in GDI +β in a call to DrawString.
None of these errors occur in Windows 7.
I tried various cleaning options without any success.
As a workaround, I tried to write the font file to disk and then load it using AddFontFile, but (in Windows 2012 R2) the font file is blocked throughout the process, so it cannot be deleted. This makes this parameter unacceptable.
Any help on getting AddMemoryFont to work continuously or getting AddFontFile to unlock a file would be greatly appreciated.