Sunday, July 4, 2010

ASP.NET Image Manipulation: ASP File as the Image Source

.NET Framework with no doubt is very extensible and has a wide range of Classes which helps you to do anything, really anything. In case of graphics/image manipulation, there is a library called GDI(Graphics Device Interface) which is a part of .NET Framework and has a wide range of classes to perform operations like Create/Edit/Draw/Save on Image/Graphics. The scope of this article will be to opening a image file and sending Response as image which is Binary, so an ASP file (.aspx) act as the Image File which can be used inside the Generic <img> tag as the source. All of the code will be in C#.

Importing Namespaces

First we need to import the Namespaces which allow us to use GDI Classes.

using System.Drawing;
using System.Drawing.Imaging;

Writing Image to Response

Next, we will write the code which will read the image and trigger it to Response.

Bitmap imgNew;

imgNew = new Bitmap(Server.MapPath("~/Goldentemple.jpg"));
imgNew.Save(Response.OutputStream, ImageFormat.Jpeg);

First, we create an instance of the class Bitmap. Bitmap class is very flexible, we can do many different operation on image like rotating, flipping etc. Then we create a new object of Bitmap class and specifying file path. Using Server.MapPath is always preferred. Next, we Save the image to our OutputStream i.e. the HTML output that will be send back to browser on a request. Last, we free all memory of object.

Here we Go!

That’s all. We’re done now. Just specify the file name in the source property of <img> tag. In my case, it’s Image.aspx.

<img src="Image.aspx" />

Download Source Code

Code we have used so far in bundled in a Project, which can be downloaded here (not available now). It’s in C#.

What’s Next?

As I said, scope of this article is to keep it very simple. There are immense possibilities, that can happen. For further advancement in this, I prefer you to read following articles.

No comments:

Post a Comment