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