Simon
Simon

Reputation: 492

How could you save the text from a Textbox or Label in winforms as an image?

I simply want to add some text to either a textbox or a label in winforms and then save that text as an image like jpeg/bmp. Is this possible?

Upvotes: 1

Views: 2836

Answers (3)

brendonofficial
brendonofficial

Reputation: 910

You can use the Graphics class to draw your text on to a new Bitmap object. The below script turns the Bitmap in to an Image object, which you can then apply it's use somewhere, or save to disk.

// Our text to paint
String str = "This is my text.";

// Create our new bitmap object
Bitmap bmp = new Bitmap(128, 128);
Image img = Image.FromHbitmap(bmp.GetHbitmap());

// Get our graphics object
Graphics g = Graphics.FromImage(img);
g.Clear(Color.White);

// Define our image padding
var imgPadding = new Rectangle(2, 2, 2, 2);

// Determine the size of our text, using our specified font.
Font ourFont = new Font(
    FontFamily.GenericSansSerif,
    12.0f,
    FontStyle.Regular,
    GraphicsUnit.Point
);
SizeF strSize = g.MeasureString(
    str,
    ourFont,
    (bmp.Width - imgPadding.Left - imgPadding.Right),
    StringFormat.GenericDefault
);

// Create our brushes
SolidBrush textBrush = new SolidBrush(Color.DodgerBlue);

// Draw our string to the bitmap using our graphics object
g.DrawString(str, ourFont, textBrush, imgPadding.Left, imgPadding.Top);

// Flush
g.Flush(System.Drawing.Drawing2D.FlushIntention.Sync);

// Save our image.
img.Save("myImage.png", System.Drawing.Imaging.ImageFormat.Png);

// Clean up
textBrush.Dispose();
g.Dispose();
bmp.Dispose();

Hope this helps.

Upvotes: 0

Cyril Gandon
Cyril Gandon

Reputation: 17068

The DrawToBitmap method of the Control class will help you:

var bitmap = new Bitmap(this.textbox.Width, this.textbox.Height);
this.textbox.DrawToBitmap(bitmap, new Rectangle(0, 0, bitmap.Width, bitmap.Height));

Note that you will have the full appearance of the textbox: border, background color, etc.

Upvotes: 2

user1567896
user1567896

Reputation: 2398

With this code you can create a screenshot of any given control. In this case of your textbox or label:

private Bitmap CaptureControl(Control ctl)
{
    Rectangle rect;

    if (ctl is Form)
        rect = new Rectangle(ctl.Location, ctl.Size);
    else
        rect = new Rectangle(ctl.PointToScreen(new Point(0, 0)), ctl.Size);

    Bitmap bitmap = new Bitmap(rect.Width, rect.Height, PixelFormat.Format64bppPArgb);

    using (Graphics g = Graphics.FromImage(bitmap))
    {
        g.CopyFromScreen(rect.Left, rect.Top, 0, 0, bitmap.Size, CopyPixelOperation.SourceCopy);
    }

    return bitmap;
}

Upvotes: 1

Related Questions