Introduction to WebImage

Posted by Matthew Osborn on July 2, 2010

One common operation that pretty much every website in the world does is either accepting, creating, editing, or displaying images. This could be something as simple as a user’s profile picture or as complex a full blown image gallery. Either way if you have every had implement these functionalities in a website you know that they are not the easiest thing to create. Well, here is where the WebPages team comes in to save the day! We have wrapped what we think are some of the most common image manipulation operations into a brand new fancy WebImage helper. </p>

Okay so what can the WebImage helper do for you, well a few things:

  • Get an image from the request
  • Resize
  • Crop
  • Add a watermark (text and image)
  • Flip vertical and horizontal
  • Rotate right and left
  • Save and convert formats
  • Some other more boring stuff like get the array of bytes, blah blah blah.

Okay so now that I got you all excited about the WebImage helper (it’s okay if you’re not I will forgive you) let jump into some code.

So one of the more common things to do is to allow a user to upload an image and then save it off somewhere, either to a database or the file system. So I am going to stop here and say that for the rest of the article I will assume you have a basic understand of HTML and that I don’t need to show you how to create a file upload input on your page.

  1. var photoToDatabase = WebImage.GetImageFromRequest("FileUploadNameHere");
  2. repo.SaveToDatabase(photoToDatabase.GetBytes());
  3.  
  4. /* OR */
  5.  
  6. var photoToFileSystem = WebImage.GetImageFromRequest("FileUploadNameHere");
  7. string newFileName = Guid.NewGuid().ToString() + "_" + photoToFileSystem.FileName;
  8. photoToFileSystem.Save("~\\images\\" + newFileName);

In the code sample above you can see two different ways to grab the uploaded file from the request (the input has a name of ‘FileUploadNameHere’) and save it off, either to a database or to the file system. The first example shows how to save it up to a database. Most of the time the API for saving to a database just take a Byte[] of the image, for instance see the Simple Data demo. The second one that save the image off to the file system is the much more interesting sample. For right now ignore the man behind the current (line number seven) in the sample that just ensures a unique file name. The team to trying to see what we can do to make this a better story but no promises. So if you’ll notice there is a native API that we are called, called Save. This method takes in a path, which can be a relative path like it is in the sample or a a full path (you would PhysicalApplicationPath to create such a path), and saves a copy of the image to the file system.

Okay so let’s do something a little more interesting, let’s talk about what you how you would take that image that you just saved off and then create a thumbnail version of it.

  1. var photoToDatabase = WebImage.GetImageFromRequest("FileUploadNameHere");
  2. photoToDatabase.Clone().Resize(128, 128, preserveAspectRatio: true);
In this example there are two APIs that I would like to take the time to point out. The first is the call to the Clone method, this effectively create a copy of the image in memory. The reason for this is that we want to still have the original image preserved, assuming we are also going to save it of. The second is the call to the Resize method, it takes a height and a width and has a two optional parameters. In this example I am using the preserveAspectRatio parameter, which will choose a height and a width that matches as closely to the values you passed in while still keeping the aspect ratio. This would be a good time to stop and point out that all the WebImage APIs are designed to return a WebImage so you get a fluent design when using them. In the example above you can see how I was able to chain multiple API calls together into one line, which in my humble opinion looks much cleaner. Now that you have a basic understanding of how the WebImage API works, and can explore the remaining APIs, I’d like to leave you with a sample how you can write a page that takes an users uploaded photo adds whatever text they provided as a watermark and then allows them to download the image.
  1. @{
  2.         WebImage photo = null;
  3.         var newFileName = "";
  4.         var imagePath = "";
  5.         var imageThumbPath  = "";
  6.         if(IsPost){
  7.             photo = WebImage.GetImageFromRequest("Image");
  8.             if(photo != null){
  9.                 /*Setup Correct Image Paths*/
  10.                 newFileName = Guid.NewGuid().ToString() + "_" + Path.GetFileName(photo.FileName);
  11.                 imagePath = "~\\images\\" + newFileName;
  12.                 imageThumbPath = "~\\images\\thumbs\\" + newFileName;
  13.                 /*Add Text Watermark*/
  14.                 var text = Request["Text"];
  15.                 var opacity = Request["Opacity"].AsInt();
  16.                 var fontSize = Request["FontSize"].AsInt();
  17.                 photo.AddTextWatermark(text, fontSize: fontSize, opacity: opacity);
  18.                 /*Add Image Watermark*/
  19.                 var WMImage = WebImage.GetImageFromRequest("WMImage");
  20.                 if(WMImage != null){
  21.                     photo.AddImageWatermark(WMImage, verticalAlign: "Top", opacity: opacity);
  22.                 }
  23.                 /*Save and Create Thumbnail*/
  24.                 photo.Save(imagePath);
  25.                 photo.Resize(350, 350, preserveAspectRatio: true).Save(imageThumbPath);
  26.             }
  27.         }
  28. }
  29.  
  30. <!DOCTYPE html>
  31.  
  32. <html xmlns="http://www.w3.org/1999/xhtml">
  33. <head>
  34.     <title>ASP.NET WebPages | WebImage Demo</title>
  35.     <link type="text/css" rel="Stylesheet" href="default.css" />
  36. </head>
  37. <body>
  38.     <form action=""  method="post" enctype="multipart/form-data">
  39.         <fieldset>
  40.             <legend>WebImage Demo</legend>
  41.                 <label for="Image">Image</label>
  42.                 <input type="file" name="Image" />
  43.                 <label for="Text">Watermark Image</label>
  44.                 <input type="file" name="WMImage" />
  45.                 <label for="Text">Watermark Text</label>
  46.                 <input type="text" name="Text" value="WebImage Demo" />
  47.                 <label for="Opacity">Opacity (0-100)</label>
  48.                 <input type="text" name="Opacity" value="80" />
  49.                 <label for="FontSize">Font Size</label>
  50.                 <input type="text" name="FontSize" value="60" />
  51.                 <input type="submit" value="Try It Out" />
  52.         </fieldset>
  53.     </form>
  54.     @if(imagePath != ""){
  55.     <div class="result">        
  56.         <img src="@Href(imageThumbPath)" alt="Your image with a watermarl" />
  57.         <a href="@Href(imagePath)" target="_blank" class="download">Download Full Size</a>
  58.     </div>
  59.     }
  60. </body>
  61. </html>

Q&A:

Question: Where can I find the dll that has WebImage?
Answer: WebImage is part of the WebMatrix stack, specifically ASP.NET WebPages. WebImage is in the Microsoft.WebPages.Helpers assembly that is GAC'd and also drop in program files when you install the stack.