Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding text to an image file

Tags:

c#

I need to add text to an image file. I need to read one image file (jpg,png,gif) and I need add one line text to it.

like image 356
RV. Avatar asked Apr 02 '09 12:04

RV.


1 Answers

Well in GDI+ you would read in the file using a Image class and then use the Graphics class to add text to it. Something like:

  Image image = Image.FromFile(@"c:\somepic.gif"); //or .jpg, etc...
  Graphics graphics = Graphics.FromImage(image);
  graphics.DrawString("Hello", this.Font, Brushes.Black, 0, 0);

If you want to save the file over the old one, the code has to change a bit as the Image.FromFile() method locks the file until it's disposed. The following is what I came up with:

  FileStream fs = new FileStream(@"c:\somepic.gif", FileMode.Open, FileAccess.Read);
  Image image = Image.FromStream(fs);
  fs.Close();

  Bitmap b = new Bitmap(image);
  Graphics graphics = Graphics.FromImage(b);
  graphics.DrawString("Hello", this.Font, Brushes.Black, 0, 0);

  b.Save(@"c:\somepic.gif", image.RawFormat);

  image.Dispose();
  b.Dispose();

I would test this quite thoroughly though :)

like image 134
Mladen Mihajlovic Avatar answered Oct 08 '22 01:10

Mladen Mihajlovic