Manipulating images in .NET involves using the System.Drawing namespace, namely the Bitmap, its parent class Image, and Graphics classes. What I want to show with this post is that it is possible to transform an image that is already saved on the file system, or one that is referenced by a URL. So if your app has its own images, or you want to link to a served image on a different site, we can still manipulate the images and display them using the output stream. It's actually quite simple, but perhaps often overlooked.
My setup for this test involves creating an image using either web or html controls, and setting the source of that image to a URL. In my case, my URL is "Imager.aspx," which is my image handling page, and a querystring parameter set to the URL of the image I am linking, http://froogle.google.com/froogle/images/froogle_110tall.gif. If I did not want to link to an image, but use one from the file system, I can change my querystring parameter to be something else. Basically my app needs to determine what to send to the Imager.aspx, which processes the image.
My Imager.aspx.cs will determine if the image source I am sending it is a URL or a file reference. I can then load my image using the following.
Bitmap bmap = new Bitmap(
System.Net.HttpWebRequest.Create(
Request.QueryString["url"]).GetResponse().GetResponseStream() );
OR
Bitmap bmap = new Bitmap( Request.QueryString["file"] );
Obviously I would check the data for errors. Now we have loaded our image from either a URL or file, and we can manipulate it however we want. In my case I will flip the image using the following.
bmap.RotateFlip(RotateFlipType.Rotate180FlipY);
Bitmap bmapTemp = new Bitmap(500,100);
Graphics gfx = Graphics.FromImage( (System.Drawing.Image) bmapTemp);
gfx.DrawImage(bmap, new Rectangle(0,0,500,100) );
Finally we save the image and dispose of all objects.
bmap.Save( Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg );
bmap.Dispose();
bmapTemp.Dispose();
gfx.Dispose();
To demonstrate the effect of this test, I have used Javascript. The end result looks like this.
