Add the text to an image

.NET API Solution to write text on images

 

Aspose.Font for .NET is a comprehensive solution for developers working with fonts in their .NET applications. It simplifies tasks like loading, editing, converting, and using fonts for different purposes. One such purpose is text rendering. The solution provides a custom way to render text on an image using a particular font, considering kerning and offering control over various aspects like background color, text color, and text size.

There are many apps where adding text to images is a helpful functionality, catering to various purposes. Here are some categories:

  • Photo editing apps - like Canva, Adobe Express, and PicLab allow you to edit photos in various ways, and adding text is a core feature.
  • Social media apps - like Instagram and Facebook have built-in text editing tools for photos. This lets you add captions, quotes, or other messages directly within the app before sharing.
  • If you’re creating more complex designs like flyers, posters, or presentations, graphic design apps like Photoshop or GIMP offer advanced text editing features. These allow for precise control over text placement, formatting, and effects.
  • Meme culture thrives on text-on-image humor. meme creation apps like Imgflip or Meme Generator provide templates and editing tools designed for creating funny or captioned images.
  • Creating eye-catching visuals for marketing campaigns often involves adding text to images. Marketing and advertising tools like Spark Post or Stencil allow you to design social media posts, flyers, or ads that incorporate text effectively.
  • Educational apps - use text on images to create infographics, study guides, or other visual learning materials.

There are many reasons to add text to images, like adding context to an image, catching the user’s attention, creating a message, etc. With Aspose.Font this functionality can be easily implemented into your C# code-based apps.

To run the examples you need:

  • Aspose.Font for .NET API which is a feature-rich, powerful and easy-to-use document manipulation and conversion API for C# platform.

  • Open the NuGet package manager, and search for Aspose.Font and install. You may also use the following command from the Package Manager Console.

Package Manager Console Command


    PM> Install-Package Aspose.Font

Steps to display text on images C#:

The provided code snippet defines a function called CustomDrawText that takes various arguments to render text on a bitmap using a specified font. Here’s a breakdown of the functionality:

  1. Retrieve the Glyphs’ IDs to represent a specific character shape within the font.
  2. Set the output bitmap’s resolution.
  3. Fill the background of the bitmap with the provided brush.
  4. Set anti-aliasing for smoother text rendering and initialize variables for glyph positioning.
  5. Render texts using the specified glyphs using the renderer.
  6. Save the final bitmap with the drawn text to the specified file.

C# Code to write text on images

    public static void CustomDrawText(string text, IFont font, double fontSize, Brush backgroundBrush, Brush textBrush, string outFile, Bitmap bitmap, double kerningCoefficient = 1, double coordinateX = 0, double coordinateY = 0)
    {
        //Get glyph identifiers for every symbol in the text line
        GlyphId[] gids = new GlyphId[text.Length];

        for (int i = 0; i < text.Length; i++)
            gids[i] = font.Encoding.DecodeToGid(text[i]);

        // Set common drawing settings
        double dpi = 300;
        double resolutionCorrection = dpi / 72; // 72 is font's internal dpi

        // Prepare the output bitmap                
        Bitmap outBitmap = bitmap;

        outBitmap.SetResolution((float)dpi, (float)dpi);

        Graphics outGraphics = Graphics.FromImage(outBitmap);
        outGraphics.FillRectangle(backgroundBrush, 0, 0, outBitmap.Width, outBitmap.Height);
        outGraphics.SmoothingMode = SmoothingMode.HighQuality;

        //Declare coordinate variables and the previous gid
        GlyphId previousGid = null;
        double glyphXCoordinate = coordinateX;
        double glyphYCoordinate = coordinateY;

        glyphYCoordinate += fontSize * resolutionCorrection;

        //The loop paints every glyph in gids
        foreach (GlyphId gid in gids)
        {
            // if the font contains the gid
            if (gid != null)
            {
                Glyph glyph = font.GlyphAccessor.GetGlyphById(gid);
                if (glyph == null)
                    continue;

                // The path that accepts drawing instructions
                GraphicsPath path = new GraphicsPath();

                // Create the IGlyphOutlinePainter implementation
                GlyphOutlinePainter outlinePainter = new GlyphOutlinePainter(path);

                // Create the renderer
                Aspose.Font.Renderers.IGlyphRenderer renderer = new Aspose.Font.Renderers.GlyphOutlineRenderer(outlinePainter);

                // Get common glyph properties
                double kerning = 0;

                // Get the kerning value

                if (previousGid != null)
                {
                    kerning = (font.Metrics.GetKerningValue(previousGid, gid) / glyph.SourceResolution) * fontSize * resolutionCorrection;
                    kerning += FontWidthToImageWith(font.Metrics.GetGlyphWidth(previousGid), glyph.SourceResolution, fontSize);
                }

                // Glyph positioning - increase the glyph X coordinate according to the kerning distance
                glyphXCoordinate += kerning * kerningCoefficient;

                // Glyph placement matrix
                TransformationMatrix glyphMatrix = new TransformationMatrix(
                        new double[]
                                { fontSize * resolutionCorrection,
                            0,
                            0,
                        // negative because of the bitmap coordinate system begins from the top
                            - fontSize*resolutionCorrection,
                            glyphXCoordinate,
                            glyphYCoordinate
                                });

                // Render the current glyph
                renderer.RenderGlyph(font, gid, glyphMatrix);

                // Fill the path
                path.FillMode = FillMode.Winding;

                outGraphics.FillPath(textBrush, path);
            }

            //Set the current gid as previous to get the correct kerning for the next glyph
            previousGid = gid;
        }

        //Save the results
        outBitmap.Save(outFile);
    }



FAQ

1. What kind of images can I use to write text on it?

APIs works best with clear, high-resolution images. Avoid blurry photos or images with complex backgrounds, as these can affect the accuracy of the text placement.

2. Can I customize the text font and style?

Yes, Aspose.Font allows you to specify font styles, sizes, and even colors for your text overlay. It offers a customized output of the text, for example, when you want to compress, stretch, rotate the text at an angle, or something else.

3. How does the API handle text placement?

It offers pre-defined placements like center or bottom alignment but it also offers a more advanced (custom) way to convert text to an image using one of RenderGlyph() Methods of GlyphOutlineRenderer Class.