Sunday, February 22, 2009

Adding Text To Image Programmatically With C#

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
}

Simple Snippet MD5 and SHA1 Hash Implementation With C#

Here is a pretty simple snippet MD5 and SHA1 Hash Service Implementation.
MD5
public static String GetMD5Hash(String input)
{
Encoder enc = Encoding.Unicode.GetEncoder();
byte[] unicodeText = new byte[input.Length * 2];
enc.GetBytes(input.ToCharArray(), 0, input.Length, unicodeText, 0, true);
MD5 md5 = new MD5CryptoServiceProvider();
byte[] result = md5.ComputeHash(unicodeText);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < result.Length; i++)
{
sb.Append(result[i].ToString("X2"));
}
return sb.ToString();
}[TestMethod]
public void Hash_MD5()
{
String Text = "Hello World!";

String Hashed = HashServices.GetMD5Hash(Text);

Console.WriteLine(Hashed);
}

SHA1
public static String GetSHA1Hash(String input)
{
Encoder enc = Encoding.Unicode.GetEncoder();
byte[] unicodeText = new byte[input.Length * 2];
enc.GetBytes(input.ToCharArray(), 0, input.Length, unicodeText, 0, true);
SHA1 sha1 = new SHA1CryptoServiceProvider();
byte[] result = sha1.ComputeHash(unicodeText);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < result.Length; i++)
{
sb.Append(result[i].ToString("X2"));
}
return sb.ToString();
}[TestMethod]
public void Hash_SHA1()
{
String Text = "Hello World!";

String Hashed = HashServices.GetSHA1Hash(Text);

Console.WriteLine(Hashed);
}

How-To Get Environment Variables And Resolve System Paths

Tonight a useful trick in order to get Environment Variables and Resolve System Paths like :

  • %windir%
  • %Programfiles%
  • ..
MSDN :

Environment Class

Provides information about, and means to manipulate, the current environment and platform. This class cannot be inherited.

Namespace: System
Assembly: mscorlib (in mscorlib.dll)

Display All Current Environment Variables

IDictionary dic = Environment.GetEnvironmentVariables();
foreach (String variable in dic.Values)
{
Console.WriteLine(variable);
}
String DirPath = "%ProgramFiles%";
String Expanded = Environment.ExpandEnvironmentVariables(DirPath);
Console.WriteLine(Expanded);

DirPath = "%windir%";
Expanded = Environment.ExpandEnvironmentVariables(DirPath);
Console.WriteLine(Expanded);

Source : http://blog.sb2.fr/post/2008/12/23/How-To-Get-Environment-Variables-And-Resolve-System-Paths.aspx

How-To Create Dynamic Image From Text

In this article I’ll provide a simple class in order to Create Dynamic Image From Text, which should be pretty useful for email obfuscation for example.

Default.aspx (2)

The TextImage Class


public class TextImage
{
#region Public Properties

public Color TextColor { get; set; }
public Color BackColor { get; set; }
public Font TextFont { get; set; }
public String Text { get; set; }

#endregion

#region Private Properties

private Brush TextBrushStyle { get; set; }
private Brush BackBrushStyle { get; set; }

#endregion

#region Constructors

public TextImage(String text)
{
Text = text;
TextColor = Color.Black;
BackColor = Color.White;
TextFont = new Font("Arial", 18, FontStyle.Bold);
}
public TextImage(String text, Color textColor, Color backColor, Font textFont)
{
Text = text;
TextColor = textColor;
TextFont = textFont;
BackColor = backColor;
}

#endregion


#region Public Methods

public Bitmap Process()
{
TextBrushStyle = new SolidBrush(TextColor);
BackBrushStyle = new SolidBrush(BackColor);

float f = TextFont.Size * 72 / 96;
Bitmap tmp = new Bitmap(Text.Length * (int)f, TextFont.Height);
using (Graphics graphic = Graphics.FromImage(tmp))
{
graphic.FillRectangle(BackBrushStyle, 0, 0, tmp.Width, tmp.Height);
graphic.DrawString(Text, TextFont, TextBrushStyle, new PointF(0, 0));
}
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
}

protected void Page_Load(object sender, EventArgs e)
{
Response.ContentType = "image/jpeg";
TextImage img = new TextImage("Hello How Are You ??");
img.BackColor = Color.White;
img.TextColor = Color.Red;
img.WriteTo(Response.OutputStream);
}

Source : http://blog.sb2.fr/post/2008/12/23/How-To-Create-Dynamic-Image-From-Text.aspx

Useful Image WaterMark Extension Method

Today i'll give you a useful Extension Method in order to Add some Text to Image that can be used in HttpHandler to display copyrighted images from Database for a Photo Store for example.

WaterMarkImageHandler.ashx

Here is the Extension Code

public static Bitmap WaterMarkImage(this Bitmap bmp, String Text)
{
Image img = new Bitmap(bmp, new Size(bmp.Width, bmp.Height));
Bitmap tmp = new Bitmap(img);
using (Graphics graphic = Graphics.FromImage(tmp))
{
SolidBrush brush = new SolidBrush(Color.FromArgb(120, 255, 255, 255));
Font font = new Font("Arial", 18, FontStyle.Bold);
graphic.DrawString(Text, font, brush, new PointF(10, 30));
}
return tmp;
}
Here is a Sample of Usage
public class WaterMarkImageHandler : 
IHttpHandler
{

public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "image/jpeg";
Image img = Bitmap.FromFile(context.Server.MapPath("~/03SC008.JPG"));
Bitmap bmp = new Bitmap(img);
bmp = bmp.WaterMarkImage("SB2 DEVELOPPERS BLOG TEST");
bmp.Save(context.Response.OutputStream, ImageFormat.Jpeg);
}

public bool IsReusable
{
get
{
return true;
}
}
}

Download Solution - WaterMarkImageHandler.zip

Source : http://blog.sb2.fr/post/2008/11/29/Useful-Image-WaterMark-Extension-Method.aspx

Cookies Extensions Methods

Tonight a simple way to manage Cookies on an ASP.NET Application with Strongly Typed Objects.

These Extensions might be improved but it's a beginning.

Here is the code

public static class CookieExtensions
{
public static void AddToCokie(this HttpCookie cok, String name, T val)
where T : struct
{
if (cok == null)
return;
if (!String.IsNullOrEmpty(cok.Values[name]))
cok.Values.Remove(name);
cok.Values.Add(name, val.ToString());
HttpContext.Current.Response.Cookies.Add(cok);
}
public static T GetCookieValue(this HttpCookie cok, String name)
where T : struct
{
if (cok == null)
return default(T);
if (String.IsNullOrEmpty(cok[name]))
return default(T);

return cok[name].ConvertTo();
}
public static T ConvertTo(this String input) where T : struct
{
T ret = default(T);

if (!string.IsNullOrEmpty(input))
{
ret = (T)Convert.ChangeType(input, typeof(T));
}

return ret;
}
}

And here is a sample of usage

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Int32 orderId = Request.Cookies["MyCookie"].GetCookieValue("OrderId");
Response.Write(orderId.ToString());
}
}

protected void Button1_Click(object sender, EventArgs e)
{
Request.Cookies["MyCookie"].AddToCokie("OrderId", Int32.Parse(this.TextBox1.Text));
}
}
Source : http://blog.sb2.fr/post/2008/11/29/ASPNET-Cookies-Extensions-Methods.aspx

ASP.NET Cookies Extensions Methods

Tonight a simple way to manage Cookies on an ASP.NET Application with Strongly Typed Objects.

These Extensions might be improved but it's a beginning.

Here is the code

public static class CookieExtensions
{
public static void AddToCokie(this HttpCookie cok, String name, T val)
where T : struct
{
if (cok == null)
return;
if (!String.IsNullOrEmpty(cok.Values[name]))
cok.Values.Remove(name);
cok.Values.Add(name, val.ToString());
HttpContext.Current.Response.Cookies.Add(cok);
}
public static T GetCookieValue(this HttpCookie cok, String name)
where T : struct
{
if (cok == null)
return default(T);
if (String.IsNullOrEmpty(cok[name]))
return default(T);

return cok[name].ConvertTo();
}
public static T ConvertTo(this String input) where T : struct
{
T ret = default(T);

if (!string.IsNullOrEmpty(input))
{
ret = (T)Convert.ChangeType(input, typeof(T));
}

return ret;
}
}

And here is a sample of usage

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Int32 orderId = Request.Cookies["MyCookie"].GetCookieValue("OrderId");
Response.Write(orderId.ToString());
}
}

protected void Button1_Click(object sender, EventArgs e)
{
Request.Cookies["MyCookie"].AddToCokie("OrderId", Int32.Parse(this.TextBox1.Text));
}
}
Source : http://blog.sb2.fr/post/2008/11/29/ASPNET-Cookies-Extensions-Methods.aspx