Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding text to image and save

In my program i allow the user to enter some text which then gets put on top of an image using the graphics.DrawString() method. When i then go to save this image, it saves it without the text.

How can i save both as one image?

I have seen a few examples but none of which have helped.

private void txtToolStripMenuItem_Click(object sender, System.EventArgs e)
    {
        Rectangle r = new Rectangle(535, 50, original_image.Width, original_image.Height);
        Image img = Image.FromFile("C:\\PCB.bmp");

        Bitmap image = new Bitmap(img);

        StringFormat strFormat = new StringFormat();

        strFormat.Alignment = StringAlignment.Center;
        strFormat.LineAlignment = StringAlignment.Center;

        Graphics g = Graphics.FromImage(image);

        g.DrawString("Hellooooo", new Font("Tahoma", 40), Brushes.White,
                r, strFormat); 

        image.Save("file_PCB.Bmp", ImageFormat.Bmp);
    }
like image 449
user1221292 Avatar asked Dec 15 '12 12:12

user1221292


1 Answers

That's because you are creating a graphics object without a canvas. You are drawing on nothing, so there is nothing that is changed by your drawing the text.

First create a copy of the image (or create a blank bitmap and draw the image on it), then create a graphics object for drawing on that image:

Graphics g = Graphics.FromImage(image_save);

Then draw the text and save the image.

like image 152
Guffa Avatar answered Oct 26 '22 23:10

Guffa