Adding text to image and save

user1221292 picture user1221292 · Dec 15, 2012 · Viewed 9.3k times · Source

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);
    }

Answer

Guffa picture Guffa · Dec 15, 2012

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.