如何在运行时从文本动态生成图像 [英] How to generate an image from text on fly at runtime

查看:31
本文介绍了如何在运行时从文本动态生成图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能指导如何从输入文本生成图像.图片可能有任何扩展名都没有关系.

Can anyone guide how to generate image from input text. Image might have any extension doesn't matter.

推荐答案

好吧,假设您想在 C# 中在图像上绘制字符串,您将需要在此处使用 System.Drawing 命名空间:

Ok, assuming you want to draw a string on an image in C#, you are going to need to use the System.Drawing namespace here:

private Image DrawText(String text, Font font, Color textColor, Color backColor)
{
    //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);

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

    //create a brush for the text
    Brush textBrush = new SolidBrush(textColor);

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

    drawing.Save();

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

    return img;

}

此代码将先测量字符串,然后创建正确大小的图像.

This code will measure the string first, and then create an image of the correct size.

如果要保存这个函数的返回值,只需调用返回图像的Save方法即可.

If you want to save the return of this function, just call the Save method of the returned image.

这篇关于如何在运行时从文本动态生成图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆