Enter text in C # to create a picture of the input text

Source: Internet
Author: User

private void Button1_Click (object sender, EventArgs e)
{
Get text
string text = This.txtName.Text;

Get Bitmap (incoming Rectangle.empty automatically calculates the wide height)
Bitmap bmp = Texttobitmap (text, This.txtName.Font, Rectangle.empty, This.txtName.ForeColor, This.txtName.BackColor);

Display with PictureBox
This.pictureBox1.Image = BMP;

Save to Desktop Save.jpg
String directory = System.Environment.GetFolderPath (System.Environment.SpecialFolder.DesktopDirectory);
Bmp. Save (Directory + "\\save.jpg", imageformat.jpeg);
}
Define a method
<summary>
Convert Text to bitmap
</summary>
<param name= "Text" ></param>
<param name= "Font" ></param>
<param name= "rect" > Rectangle for Output, text is displayed inside this rectangle, automatically calculated when empty (automatic </param>
<param name= "fontcolor" > Font color </param>
<param name= "BackColor" > Background color </param>
<returns></returns>
Private Bitmap Texttobitmap (string text, font font, Rectangle rect, color fontcolor, color backColor)
{
Graphics G;
Bitmap bmp;
StringFormat format = new StringFormat (stringformatflags.noclip);
if (rect = = Rectangle.empty)
{
BMP = New Bitmap (1, 1);
g = Graphics.fromimage (BMP);
To calculate the size of the area needed to draw the text (calculate the length based on the width), recreate the rectangular area drawing
SizeF SizeF = g.measurestring (text, font, pointf.empty, format);

int width = (int) (SizeF. Width + 1);
int height = (int) (SizeF. Height + 1);
Rect = new Rectangle (0, 0, width, height);
Bmp. Dispose ();

BMP = new Bitmap (width, height);
}
Else
{
BMP = new Bitmap (rect. Width, Rect. Height);
}

g = Graphics.fromimage (BMP);

Using the ClearType font feature
G.textrenderinghint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
G.fillrectangle (New SolidBrush (BackColor), rect);
g.DrawString (text, font, brushes.black, rect, format);
return BMP;
}

Enter text in C # to create a picture of the input text

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.