csharp 创建字符串图像

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp 创建字符串图像相关的知识,希望对你有一定的参考价值。

private static string DrawText(String text)
{

    Font font = new Font("Arial", 1024, FontStyle.Bold);
    Color textColor = Color.White;
    Color backColor = Color.FromArgb(1, 143, 36, 174);

    //first, create a dummy bitmap just to get a graphics object
    Image img = new Bitmap(1, 1);
    Graphics drawing = Graphics.FromImage(img);

    //measure the string to see how big the image needs to be
    SizeF textSize = drawing.MeasureString(text, font);

    //free up the dummy image and old graphics object
    img.Dispose();
    drawing.Dispose();

    //create a new image of the right size
    img = new Bitmap((int)textSize.Width, (int)textSize.Height);

    drawing = Graphics.FromImage(img);
    drawing.SmoothingMode = SmoothingMode.HighQuality;
    drawing.InterpolationMode = InterpolationMode.HighQualityBicubic;
    drawing.PixelOffsetMode = PixelOffsetMode.HighQuality;

    //paint the background
    drawing.Clear(backColor);

    Brush rect = new SolidBrush(backColor);
    Rectangle rectangle = new Rectangle(0, 0, 200, 200);
    drawing.FillRectangle(rect, rectangle);
    
    //create a brush for the text
    Brush textBrush = new SolidBrush(textColor);

    drawing.DrawString(text, font, textBrush, 0, 0);

    drawing.Save();

    string base64;
    using (MemoryStream ms = new MemoryStream())
    {
        img.Save(ms, ImageFormat.Jpeg);
        base64 = Convert.ToBase64String(ms.ToArray());
    }

    textBrush.Dispose();
    drawing.Dispose();

    return base64;
}

以上是关于csharp 创建字符串图像的主要内容,如果未能解决你的问题,请参考以下文章

csharp 使用带有.net的ffmpeg从视频创建缩略图图像

csharp 使用emgu-cv创建图像的Min边界矩形。

csharp 用于创建文本表的字符串构建器

csharp 这是一个从简单字符串创建TypeSyntax Roslyn Model对象的工厂。请享用!

csharp C#类检查图像文件类型

csharp C#将图像转换为jpeg