Example #1
0
        private static bool GetTextBounds(GlyphTypeface glyphTypeface, double fontSize, out double topDistance, out double bottomDistance)
        {
            string testCharacters = "aA. ÅÄÖÃÂ_[]{}()|ygf";

            topDistance    = double.MaxValue;
            bottomDistance = double.MinValue;

            for (int n = 0; n < testCharacters.Length; n++)
            {
                if (glyphTypeface.CharacterToGlyphMap.TryGetValue(testCharacters[n], out ushort glyphIndex))
                {
                    Geometry outline = glyphTypeface.GetGlyphOutline(glyphIndex, fontSize, 0);
                    topDistance    = Math.Min(topDistance, outline.Bounds.Top);
                    bottomDistance = Math.Max(bottomDistance, outline.Bounds.Bottom);
                }
            }

            if (bottomDistance == double.MinValue)
            {
                return(false);
            }

            topDistance = Math.Abs(topDistance);
            return(true);
        }
Example #2
0
        /*
         * PathGeometry pg = m_libCmn.GetFontPathGeometry("あ", 20.0, "HGP白洲太楷書体");
         * // "MS 明朝");
         * // "DF平成ゴシック体W9");
         * // "ヒラギノ特太行書");
         */
        public ClsFontPathGeometry GetFontPathGeometry(string str, double fontsize, string fontname)
        {
            char                ch;
            Uri                 uri;
            ushort              glyphIndex;
            Typeface            typeFace;
            GlyphTypeface       gt;
            Geometry            gm;
            ClsFontPathGeometry clsFGP;
            string              name, fontkey;
            int                 max, idx;

            ch          = Convert.ToChar(str);
            m_dFontSize = fontsize;
            typeFace    = new Typeface(fontname);

            RegistryKey regkey =
                Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\Windows NT\CurrentVersion\Fonts", false);

            string[] keys = regkey.GetValueNames();
            fontkey = "";
            max     = keys.Length;
            for (idx = 0; idx < max; idx++)
            {
                if (keys[idx].Contains(fontname) == true)
                {
                    fontkey = keys[idx];
                    break;
                }
            }
            if (fontkey == "")
            {
                FontFamily fm = new FontFamily(fontname);
                // fm.FamilyNames.TryGetValue(XmlLanguage.GetLanguage("en-us"), out name);
                name = fm.FamilyNames.Values.ToList()[0];
                for (idx = 0; idx < max; idx++)
                {
                    if (keys[idx].Contains(name) == true)
                    {
                        fontkey = keys[idx];
                        break;
                    }
                }
            }
            string ttname = (string)regkey.GetValue(fontkey);

            uri = new Uri("C:\\Windows\\Fonts\\" + ttname);
            //uri = new Uri(fontpath);
            gt = new GlyphTypeface(uri);
            gt.CharacterToGlyphMap.TryGetValue((int)ch, out glyphIndex);

            gm            = gt.GetGlyphOutline(glyphIndex, fontsize, fontsize);
            clsFGP        = new ClsFontPathGeometry();
            clsFGP.pg     = gm.GetOutlinedPathGeometry();
            clsFGP.dMoveY = (gt.Baseline) * fontsize;
            return(clsFGP);
        }
    public static System.Drawing.Bitmap GetBitmapOfChar(GlyphTypeface gt, _
                                                        char c, _
                                                        double ptSize, _
                                                        float dpi)
    {
        ushort ci = 0;

        if (!gt.CharacterToGlyphMap.TryGetValue(Strings.AscW(c), ci))
        {
            if (!gt.CharacterToGlyphMap.TryGetValue(Strings.Asc(c), ci))
            {
                return(null);
            }
        }

        Geometry        geo      = gt.GetGlyphOutline(ci, ptSize, ptSize);
        GeometryDrawing gDrawing = new GeometryDrawing(System.Windows.Media.Brushes.Black, null, geo);
        DrawingImage    geoImage = new DrawingImage(gDrawing);

        geoImage.Freeze();

        DrawingVisual  viz = new DrawingVisual();
        DrawingContext dc  = viz.RenderOpen;

        dc.DrawImage(geoImage, new Rect(0, 0, geoImage.Width, geoImage.Height));
        dc.Close();

        RenderTargetBitmap bmp = new RenderTargetBitmap(geoImage.Width, _
                                                        geoImage.Height, _
                                                        dpi, dpi, _
                                                        PixelFormats.Pbgra32);

        bmp.Render(viz);

        PngBitmapEncoder enc = new PngBitmapEncoder();

        enc.Frames.Add(BitmapFrame.Create(bmp));

        MemoryStream ms = new MemoryStream();

        enc.Save(ms);
        ms.Seek(0, SeekOrigin.Begin);

        enc = null;
        dc  = null;
        viz = null;

        DisposeBitmap(bmp);

        System.Drawing.Bitmap gdiBMP = new System.Drawing.Bitmap(ms);
        ms.Dispose();

        //gdiBMP.Save("c:\test.png", System.Drawing.Imaging.ImageFormat.Png)

        return(gdiBMP);
    }
Example #4
0
        static void Main(string[] args)
        {
            string        fontPath = @"C:\Users\zhdon\Desktop\lsu.ttf";
            Uri           fontUri  = new Uri(fontPath);
            GlyphTypeface gt       = new GlyphTypeface(fontUri);

            WriteLine("FONT_METRICS.glyphCount = {0}", gt.GlyphCount);
            WriteLine("FONT_METRICS.baseline = {0}", gt.Baseline);
            WriteLine("FONT_METRICS.capsHeight = {0}", gt.CapsHeight);
            WriteLine("FONT_METRICS.xHeight = {0}", gt.XHeight);
            WriteLine("FONT_METRICS.height = {0}", gt.Height);
            WriteLine("FONT_METRICS.glyphs = {0}", "GLYPHS");
            foreach (var kvp in gt.CharacterToGlyphMap)
            {
                var          code    = kvp.Key;
                var          c       = char.ConvertFromUtf32(code);
                var          i       = kvp.Value;
                const double em      = 18;
                var          g       = gt.GetGlyphOutline(i, em, em);
                var          width   = (g.Bounds.Right - g.Bounds.Left) / em;
                var          ascent  = (0 - g.Bounds.Top) / em;
                var          descent = g.Bounds.Bottom / em;
                if (double.IsInfinity(ascent) || double.IsInfinity(descent))
                {
                    continue;
                }
                WriteLine("GLYPHS[{0}] = Glyph('{1}', '{2}', {3}, {4}, {5}, {6}, {7})",
                          code,
                          c != "'" && c != "\\" ? c : "\\" + c,
                          UnicodeInfo.GetName(code).ToLower(),
                          gt.AdvanceWidths[i],
                          descent,
                          ascent,
                          gt.LeftSideBearings[i],
                          gt.RightSideBearings[i]);
            }
            Pause();
        }
Example #5
0
        static void Main(string[] args)
        {
            List <string>   charLines = new List <string>();
            DirectoryInfo   d         = new DirectoryInfo(@"D:\MachineLearning\Document Layout Analysis\Fonts");
            List <FileInfo> Files     = d.GetFiles("*.ttc").ToList(); // ttf, fon, ttc // 'fon' doesn't work

            Files.AddRange(d.GetFiles("*.ttf"));

            foreach (var fontFile in Files)
            {
                Uri           uri           = new Uri(fontFile.FullName);
                GlyphTypeface glyphTypeface = new GlyphTypeface(uri);

                foreach (var unicodePair in unicodeChars)
                {
                    //ScatterplotView view = new ScatterplotView();
                    //view.Dock = System.Windows.Forms.DockStyle.Fill;
                    //view.LinesVisible = true;

                    int  indexUnicode = unicodePair.Key;
                    char unicode      = unicodePair.Value;

                    if (!glyphTypeface.CharacterToGlyphMap.ContainsKey(indexUnicode))
                    {
                        continue;
                    }

                    var geometry = glyphTypeface.GetGlyphOutline(
                        glyphTypeface.CharacterToGlyphMap[indexUnicode],
                        100, 1);
                    var boundingBox = geometry.Bounds;

                    var stepX     = boundingBox.Width / 8;
                    var stepY     = boundingBox.Height / 8;
                    var blockArea = stepX * stepY;

                    List <int> data = new List <int>();

                    var path = geometry.GetFlattenedPathGeometry();

                    for (int j = 0; j < 8; j++)
                    {
                        for (int i = 0; i < 8; i++)
                        {
                            RectangleGeometry block = new RectangleGeometry(
                                new System.Windows.Rect(
                                    new System.Windows.Point(boundingBox.X + i * stepX, boundingBox.Y + j * stepY),
                                    new System.Windows.Point(boundingBox.X + (i + 1) * stepX, boundingBox.Y + (j + 1) * stepY)));

                            PathGeometry intersectionGeometry = PathGeometry.Combine(block, path, GeometryCombineMode.Intersect, null);
                            var          area = Math.Round(intersectionGeometry.GetArea() / blockArea * 16, 0);
                            data.Add((int)area);
                        }
                    }
                    var dataStr = string.Join(",", data);
                    dataStr += "," + indexUnicode.ToString();

                    charLines.Add(dataStr);

                    /*var figures = path.Figures.ToList();
                     *
                     * var segments = figures.Select(f => f.Segments.ToList()).ToList();
                     *
                     * foreach (var group in segments)
                     * {
                     *  foreach (var segment in group)
                     *  {
                     *      if (segment is PolyLineSegment polyLineSegment)
                     *      {
                     *          var points = polyLineSegment.Points.ToList();
                     *          var x = points.Select(p => (p.X / (boundingBox.X + boundingBox.Width)) * 8.0).ToArray();
                     *          var y = points.Select(p => -(p.Y / (boundingBox.Height)) * 8.0).ToArray();
                     *
                     *          view.Graph.GraphPane.AddCurve(unicode.ToString(),
                     *              x, y,
                     *              System.Drawing.Color.Black);
                     *
                     *      }
                     *      else if (segment is ArcSegment arcSegment)
                     *      {
                     *          throw new NotImplementedException();
                     *      }
                     *      else if (segment is BezierSegment bezierSegment)
                     *      {
                     *          throw new NotImplementedException();
                     *      }
                     *      else if (segment is LineSegment lineSegment)
                     *      {
                     *          throw new NotImplementedException();
                     *      }
                     *      else if (segment is PolyBezierSegment polyBezierSegment)
                     *      {
                     *          throw new NotImplementedException();
                     *      }
                     *      else if (segment is PolyQuadraticBezierSegment polyQuadraticBezierSegment)
                     *      {
                     *          throw new NotImplementedException();
                     *      }
                     *      else if (segment is QuadraticBezierSegment quadraticBezierSegment)
                     *      {
                     *          throw new NotImplementedException();
                     *      }
                     *      else
                     *      {
                     *          throw new ArgumentException(segment.GetType().ToString());
                     *      }
                     *  }
                     * }*/

                    //view.Graph.GraphPane.AxisChange();
                    //var f1 = new System.Windows.Forms.Form();
                    //f1.Width = 1000;
                    //f1.Height = 1000;
                    //f1.Controls.Add(view);
                    //f1.ShowDialog();
                }
            }

            File.WriteAllLines(@"D:\MachineLearning\Document Layout Analysis\Fonts\chars-train.csv", charLines);
        }