Writing text as image in ASP.NET MVC

Sheonarayan
Posted by Sheonarayan under ASP.NET MVC category on | Points: 40 | Views : 1279
On the wake of email extractor software, there is a practice to convert the image as text and show as an image on the website. Below is the code snippet that converts the text as an image and show on the page.

Create a controller action method below


public FileResult WriteTextAsImage(string id, int? width, int? height)
{
int textSize = 10;
if (!width.HasValue)
{
width = 225;
}

if (!height.HasValue)
{
height = 20;
}

Response.ContentType = "image/jpeg";
string textToWrite = id;
string[] s = textToWrite.Split('|');
textToWrite = textToWrite.Replace("|", "\n");


if (textToWrite.Trim().Length > 0)
{
Bitmap image = new Bitmap(width.Value, height.Value);
Graphics g = null;
try
{
using (var stream = new MemoryStream())
{
g = Graphics.FromImage(image);
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
Font f = new Font("Verdana", textSize, FontStyle.Regular);
SolidBrush b = new SolidBrush(Color.White);
g.FillRectangle(b, 0, 0, width.Value, height.Value);
g.DrawString(textToWrite, f, Brushes.Blue, 2, 3);
g.DrawLine(new Pen(Color.Black, 1), new Point(5, 25), new Point(100, 0));

f.Dispose();
image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
return File(stream.ToArray(), "image/jpeg");
}
}
catch (Exception ee)
{
throw;
}
finally
{
image.Dispose();
g.Dispose();
}
}
else
{
return File("", "");
}
}


On the view page , write following code (assuming your action method is in HomeController.cs)

<img src="/Home/WriteTextAsImage/?id=abc@gmail.com" />


Here abc@gmail.com will be converted as an image and will be shown on the website.

Comments or Responses

Login to post response