D B D B - 1 month ago 15
ASP.NET (C#) Question

Add text to image without saving

I want to be able to apply some text over a banner image in C#. So far i have a class control that pulls through the title, href and image src but i want to add text to it without saving it.

So i want to use the title i pulled through and apply it ontop.

Below is graphics i have attempted to apply to it. I just want to overlay text on it, not create a new image as well.

private void GenerateBannerTitle()
{
Bitmap bannerSource = new Bitmap(PhysicalBannerPath);
//bannerSource.Save(PhysicalBannerPath);
RectangleF rectf = new RectangleF(430, 50, 650, 50);

using (Graphics g = Graphics.FromImage(bannerSource))
{
g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
g.DrawString("hfsdfdsfds", new Font("courier sans", 100, FontStyle.Bold), Brushes.White, rectf);
}
}


Any help or ideas. Can this be done via inline css in c# or can there be a way to alter what i have now to just apply it ontop.

At the moment i am just pulling through the image. Its just applying text that i need to understand and get working.

Answer

Use a memory stream to return the image as a base64 string

private string GenerateBannerTitle()
    {
        var bitmap = new Bitmap(PhysicalBannerPath);
        RectangleF rectf = new RectangleF(430, 50, 650, 50);

        using (var g = Graphics.FromImage(bitmap))
        {
            using (var arialFont = new Font("Arial", 10))
            {
                g.SmoothingMode = SmoothingMode.AntiAlias;
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                g.PixelOffsetMode = PixelOffsetMode.HighQuality;
                g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
                g.DrawString("hfsdfdsfds", new Font("courier sans", 100, FontStyle.Bold), Brushes.White, rectf);
            }
        }


        var ms = new MemoryStream();

        bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

        var arr = new byte[ms.Length];

        ms.Position = 0;
        ms.Read(arr, 0, (int)ms.Length);
        ms.Close();

        var strBase64 = Convert.ToBase64String(arr);

        return strBase64;

    }

And the show it in html like:

<img src="data:image/jpg;base64,the returned data"/>