RV.
RV.

Reputation: 2842

Adding text to an image file

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.

Upvotes: 11

Views: 21497

Answers (3)

OmG
OmG

Reputation: 18838

Specifically for gifs to have a gif result, you should write on each frame like the following:

string originalImgPath = @"C:\test.gif";
Image IMG = Image.FromFile(originalImgPath);
FrameDimension dimension = new FrameDimension(IMG.FrameDimensionsList[0]);
int frameCount = IMG.GetFrameCount(dimension);
int Length = frameCount;
GifBitmapEncoder gEnc = new GifBitmapEncoder();
for (int i = 0; i < Length; i++)
{
    // Get each frame
    IMG.SelectActiveFrame(dimension, i);
    var aFrame = new Bitmap(IMG);

    // write one the selected frame
    Graphics graphics = Graphics.FromImage(aFrame);
    graphics.DrawString("Hello", new Font("Arial", 24, System.Drawing.FontStyle.Bold), System.Drawing.Brushes.Black, 50, 50);
    var bmp = aFrame.GetHbitmap();
    var src = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                bmp,
                IntPtr.Zero,
                Int32Rect.Empty,
                BitmapSizeOptions.FromEmptyOptions());
    // merge frames
    gEnc.Frames.Add(BitmapFrame.Create(src));
}

string saveImgFile = @"C:\modified_test.gif"
using (FileStream fs2 = new FileStream(saveImgFile, FileMode.Create))
{
    gEnc.Save(fs2);
}

I should have mentioned that getting gif frames from this post.

Upvotes: 1

Mladen Mihajlovic
Mladen Mihajlovic

Reputation: 6435

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 :)

Upvotes: 21

nba bogdan
nba bogdan

Reputation: 123

You can do this by using the Graphics object in C#. You can get a Graphics object from the picture ( image.CreateGraphics() - or something like this as I remember ) and the use some of the built in methods for adding text to it like : Graphycs.DrawString() or other related methods.

Upvotes: 0

Related Questions