In this article I’ll continue talk about Adding Text To Image using an Extension Method in my previous article.
I’ll provide here a more useful and complete Class to Add Text To Image Programmatically with C#.
WaterMarkImage
This class is able to :
- Add Text to Image
- Render it through a Stream (like HttpContext.Current.Response.OutputStream)
- Render it to Image File
public class WaterMarkImage
{
#region Private Properties
private Bitmap OriginalImage { get; set; }
#endregion
#region Public Properties
public Color TextColor { get; set; }
public Brush BrushStyle { get; set; }
public Font TextFont { get; set; }
public String Text { get; set; }
public PointF Position { get; set; }
#endregion
#region Constructors
public WaterMarkImage(String filename)
: this(new Bitmap(filename))
{
}
public WaterMarkImage(Bitmap bmp)
{
OriginalImage = bmp;
TextColor = Color.White;
BrushStyle = new SolidBrush(TextColor);
TextFont = new Font("Arial", 18, FontStyle.Bold);
}
#endregion
#region Public Methods
public Bitmap Process()
{
Bitmap tmp = new Bitmap(OriginalImage);
using (Graphics graphic = Graphics.FromImage(tmp))
{
if (Position == null)
{
Position = new PointF(10, 30);
}
graphic.DrawString(Text, TextFont, BrushStyle, Position);
}
return tmp;
}
public void WriteTo(Stream stream)
{
Bitmap bmp = Process();
if (bmp == null) return;
bmp.Save(stream, ImageFormat.Jpeg);
}
public void WriteTo(String filename)
{
Bitmap bmp = Process();
if (bmp == null) return;
bmp.Save(filename, ImageFormat.Jpeg);
}
#endregion
}