How to resize an image with .NET (C#)

April 03, 2009

How to resize an image with .NET

In last article I described how to resize an image using PHP, and somebody asked me to provide same example in .NET. So here is a sample C# code for resizing an image on he fly. Once again I want to mention that it is better to resize an image when it is being saved, so you would not have to resize it on the fly.

<%@ Page Language="C#" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Drawing" %>
<%@ Import Namespace="System.Drawing.Imaging" %>
<%@ Import Namespace="System.Drawing.Drawing2D" %>
<script runat="server" type="text/C#">
protected void Page_Load(object sender, EventArgs e)
{
	try
	{
		string sFileName = "", ext="Jpeg";
		string noImageFilePath = "folder/no_image.jpg"; //What to display if no image found
		double new_height = 300, new_width = 300;
		if(Request["image_path"].ToString()!="")
		{                                                         
			sFileName = Request.MapPath("/") + Request["image_path"].ToString().Substring(1);
			ext = sFileName.Substring(sFileName.LastIndexOf(".")+1);
			Response.ContentType = "image/" + ext; 
		}
		if(!File.Exists(sFileName))
		{
			sFileName = Request.MapPath("/") + noImageFilePath;
			Response.ContentType = "image/Jpeg";
		}
		Bitmap bmp = new Bitmap(sFileName);
		double ih = bmp.Height, iw = bmp.Width, temp_height = 0, temp_width = 0, new_height = 0, new_width = 0;
		//Values from quarry string for needed height and width
		if (Request["h"] != null) new_height = Convert.ToDouble(Request["h"]); else new_height = 300;
		if (Request["w"] != null) new_width = Convert.ToDouble(Request["w"]); else new_width = 300;
		temp_width = iw; temp_height = ih;
		if (iw / ih > new_width / new_height)
		{
			if (iw > new_width)
			{ 
				temp_width = new_width;
				temp_height = temp_width * ih / iw;
			}
		}
		else
		{
			if (ih > new_height)
			{
				temp_height = new_height;
				temp_width = temp_height * iw / ih;
			}
		}
		Bitmap bmp1 = new Bitmap(bmp, Convert.ToInt16(temp_width), Convert.ToInt16(temp_height));
		//type text on picture
		string s_text="some text";
		using(Graphics g = Graphics.FromImage(bmp1))
		{
			g.DrawString(s_text, new Font("tahoma", 12f), new  SolidBrush(Color.Black), new Point(10,10));
		}
		Response.Clear();
		Response.ContentType = "image/png";
		using(MemoryStream stream = new MemoryStream())
		{
			if (ext == "png") {bmp1.Save(stream, ImageFormat.Png);}
			else if(ext == "gif"){bmp1.Save(stream, ImageFormat.Gif);}
			else {bmp1.Save(stream, ImageFormat.Jpeg);}
			stream.WriteTo(Response.OutputStream);
		}
		bmp1.Dispose();
		bmp.Dispose();
	}
	catch (Exception ee) { Response.Write(ee.ToString()); }
}
</script>


Michael Pankratov