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);
}
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.
You can try below code, we used it for watermark image.
System.Drawing.Image bitmap = (System.Drawing.Image)Bitmap.FromFile(Server.MapPath("image\\img_tripod.jpg")); // set image
Font font = new Font("Arial", 20, FontStyle.Italic, GraphicsUnit.Pixel);
Color color = Color.FromArgb(255, 255, 0, 0);
Point atpoint = new Point(bitmap.Width / 2, bitmap.Height / 2);
SolidBrush brush = new SolidBrush(color);
Graphics graphics = Graphics.FromImage(bitmap);
StringFormat sf = new StringFormat();
sf.Alignment = StringAlignment.Center;
sf.LineAlignment = StringAlignment.Center;
graphics.DrawString(watermarkText, font, brush, atpoint, sf);
graphics.Dispose();
MemoryStream m = new MemoryStream();
bitmap.Save(m, System.Drawing.Imaging.ImageFormat.Jpeg);
m.WriteTo(Response.OutputStream);
m.Dispose();
base.Dispose();