Working with Images in an ASP.NET Web Pages (Razor) Site

by Tom FitzMacken

This article shows you lot how to add together, display, and manipulate images (resize, flip, and add together watermarks) in an ASP.Cyberspace Web Pages (Razor) website.

What you'll learn:

  • How to add together an prototype to a folio dynamically.
  • How to let users upload an image.
  • How to resize an epitome.
  • How to flip or rotate an image.
  • How to add a watermark to an image.
  • How to use an image as a watermark.

These are the ASP.NET programming features introduced in the article:

  • The WebImage helper.
  • The Path object, which provides methods that permit you dispense path and file names.

Software versions used in the tutorial

  • ASP.Net Web Pages (Razor) 2
  • WebMatrix 2

This tutorial also works with WebMatrix 3.

Calculation an Paradigm to a Web Page Dynamically

You lot can add images to your website and to individual pages while you lot're developing the website. You can likewise permit users upload images, which might be useful for tasks like letting them add together a profile photo.

If an epitome is already available on your site and you simply want to display it on a folio, you use an HTML <img> element like this:

              <img src="images/Photo1.jpg" alt="Sample Photo" />                          

Sometimes, though, you demand to exist able to display images dynamically — that is, you don't know what image to display until the folio is running.

The procedure in this section shows how to display an epitome on the fly where users specify the image file name from a list of image names. They select the proper name of the image from a driblet-down list, and when they submit the folio, the prototype they selected is displayed.

[image]

  1. In WebMatrix, create a new website.

  2. Add together a new folio named DynamicImage.cshtml.

  3. In the root folder of the website, add together a new folder and name information technology images.

  4. Add four images to the images folder you lot just created. (Any images you accept handy volition do, simply they should fit onto a page.) Rename the images Photo1.jpg, Photo2.jpg, Photo3.jpg, and Photo4.jpg. (Y'all won't use Photo4.jpg in this process, but you'll use it after in the article.)

  5. Verify that the four images are not marked as read-merely.

  6. Replace the existing content in the page with the following:

                      @{  var imagePath= "";     if( Asking["photoChoice"] != zero){         imagePath = @"images\" + Request["photoChoice"];    } } <!DOCTYPE html> <html> <head>   <championship>Brandish Epitome on the Fly</title> </head> <body> <h1>Displaying an Image On the Fly</h1> <grade method="post" activity="">     <div>         I want to run into:         <select proper name="photoChoice">             <option value="Photo1.jpg">Photograph ane</selection>             <option value="Photo2.jpg">Photograph 2</option>             <option value="Photo3.jpg">Photo iii</choice>         </select>         &nbsp;         <input blazon="submit" value="Submit" />     </div>     <div style="padding:10px;">         @if(imagePath != ""){             <img src="@imagePath" alt="Sample Image" width="300px" />         }     </div> </form> </body> </html>                                  

    The body of the page has a drop-downwardly listing (a <select> chemical element) that'due south named photoChoice. The list has three options, and the value attribute of each listing option has the proper noun of 1 of the images that you put in the images folder. Substantially, the list lets the user select a friendly name similar "Photo 1", and information technology and so passes the .jpg file name when the page is submitted.

    In the code, you can get the user's selection (in other words, the image file name) from the list by reading Request["photoChoice"]. You first meet if there'due south a choice at all. If there is, you construct a path for the image that consists of the name of the folder for the images and the user's prototype file name. (If you tried to construct a path simply there was zero in Request["photoChoice"], you'd go an fault.) This results in a relative path like this:

    images/Photo1.jpg

    The path is stored in variable named imagePath that you'll need later in the folio.

    In the torso, at that place's also an <img> chemical element that's used to display the paradigm that the user picked. The src aspect isn't set to a file name or URL, similar you'd do to display a static element. Instead, it'southward set to @imagePath, meaning that it gets its value from the path you set in code.

    The first time that the page runs, though, there'due south no paradigm to display, because the user hasn't selected anything. This would normally hateful that the src attribute would be empty and the image would bear witness up every bit a red "x" (or whatever the browser renders when it can't find an image). To prevent this, you put the <img> element in an if cake that tests to run into whether the imagePath variable has anything in it. If the user made a selection, imagePath contains the path. If the user didn't pick an image or if this is the first time the page is displayed, the <img> chemical element isn't even rendered.

  7. Salve the file and run the page in a browser. (Make sure the page is selected in the Files workspace earlier you run it.)

  8. Select an image from the drib-downwardly list and then click Sample Image. Make sure that you see unlike images for unlike choices.

Uploading an Image

The previous example showed you how to brandish an image dynamically, simply information technology worked only with images that were already on your website. This process shows how to let users upload an image, which is then displayed on the page. In ASP.Cyberspace, y'all tin can manipulate images on the wing using the WebImage helper, which has methods that allow yous create, manipulate, and save images. The WebImage helper supports all the mutual web paradigm file types, including .jpg, .png, and .bmp. Throughout this article, yous'll employ .jpg images, but y'all can use whatsoever of the prototype types.

[image]

  1. Add together a new page and proper name information technology UploadImage.cshtml.

  2. Supplant the existing content in the folio with the following:

                      @{  WebImage photograph = naught;     var newFileName = "";     var imagePath = "";      if(IsPost){         photo = WebImage.GetImageFromRequest();         if(photo != null){             newFileName = Guid.NewGuid().ToString() + "_" +                 Path.GetFileName(photo.FileName);             imagePath = @"images\" + newFileName;              photo.Save(@"~\" + imagePath);         }     } } <!DOCTYPE html> <html> <caput>   <title>Image Upload</title> </caput> <body>   <course activeness="" method="mail" enctype="multipart/form-data">     <fieldset>       <legend> Upload Image </legend>       <characterization for="Image">Image</label>       <input blazon="file" name="Image" />       <br/>       <input type="submit" value="Upload" />     </fieldset>   </class>   <h1>Uploaded Image</h1>     @if(imagePath != ""){     <div class="result">         <img src="@imagePath" alt="prototype" />      </div>     } </trunk> </html>                                  

    The body of the text has an <input blazon="file"> chemical element, which lets users select a file to upload. When they click Submit, the file they picked is submitted along with the form.

    To get the uploaded image, yous employ the WebImage helper, which has all sorts of useful methods for working with images. Specifically, you use WebImage.GetImageFromRequest to get the uploaded image (if any) and store it in a variable named photo.

    A lot of the piece of work in this example involves getting and setting file and path names. The issue is that y'all want to get the proper noun (and merely the name) of the image that the user uploaded, so create a new path for where you're going to shop the image. Considering users could potentially upload multiple images that have the same proper noun, you utilize a bit of extra code to create unique names and make sure that users don't overwrite existing pictures.

    If an epitome actually has been uploaded (the test if (photo != null)), you get the epitome name from the image'southward FileName property. When the user uploads the image, FileName contains the user'southward original name, which includes the path from the user'southward estimator. It might look similar this:

    C:\Users\Joe\Pictures\SamplePhoto1.jpg

    You don't desire all that path information, though — you merely desire the actual file proper name (SamplePhoto1.jpg). You can strip out just the file from a path by using the Path.GetFileName method, like this:

                      Path.GetFileName(photo.FileName)                                  

    You then create a new unique file name by adding a GUID to the original name. (For more than about GUIDs, see Nigh GUIDs later on in this article.) Then y'all construct a complete path that you tin can apply to salve the image. The salve path is made upward of the new file name, the binder (images), and the current website location.

    Notation

    In order for your lawmaking to save files in the images folder, the awarding needs read-write permissions for that folder. On your development figurer this is not typically an result. However, when you publish your site to a hosting provider's spider web server, you lot might need to explicitly ready those permissions. If y'all run this code on a hosting provider'southward server and get errors, check with the hosting provider to find out how to fix those permissions.

    Finally, you laissez passer the save path to the Save method of the WebImage helper. This stores the uploaded image nether its new name. The salvage method looks similar this: photograph.Save(@"~\" + imagePath). The consummate path is appended to @"~\", which is the current website location. (For information well-nigh the ~ operator, come across Introduction to ASP.NET Web Programming Using the Razor Syntax.)

    Equally in the previous example, the body of the page contains an <img> element to display the image. If imagePath has been fix, the <img> element is rendered and its src attribute is set to the imagePath value.

  3. Run the page in a browser.

  4. Upload an epitome and make certain it'due south displayed in the page.

  5. In your site, open up the images folder. You see that a new file has been added whose file name looks something like this::

    45ea4527-7ddd-4965-b9ca-c6444982b342_MyPhoto.png

    This is the image that you uploaded with a GUID prefixed to the name. (Your own file volition accept a different GUID and probably is named something different than MyPhoto.png.)

Tip

About GUIDs

A GUID (globally-unique ID) is an identifier that's usually rendered in a format like this: 936DA01F-9ABD-4d9d-80C7-02AF85C822A8. The numbers and letters (from A-F) differ for each GUID, but they all follow the design of using groups of 8-4-4-4-12 characters. (Technically, a GUID is a sixteen-byte/128-chip number.) When y'all need a GUID, you tin telephone call specialized code that generates a GUID for you. The idea backside GUIDs is that betwixt the enormous size of the number (three.4 ten 1038) and the algorithm for generating it, the resulting number is virtually guaranteed to be 1 of a kind. GUIDs therefore are a practiced style to generate names for things when y'all must guarantee that y'all won't employ the same name twice. The downside, of course, is that GUIDs aren't particularly user friendly, and then they tend to be used when the name is used just in code.

Resizing an Image

If your website accepts images from a user, you lot might want to resize the images before you display or save them. You tin over again use the WebImage helper for this.

This procedure shows how to resize an uploaded image to create a thumbnail so save the thumbnail and original image in the website. Yous display the thumbnail on the folio and use a hyperlink to redirect users to the full-sized image.

[image]

  1. Add a new page named Thumbnail.cshtml.

  2. In the images binder, create a subfolder named thumbs.

  3. Replace the existing content in the folio with the following:

                      @{       WebImage photo = null;     var newFileName = "";     var imagePath = "";     var imageThumbPath  = "";      if(IsPost){         photograph = WebImage.GetImageFromRequest();         if(photo != null){              newFileName = Guid.NewGuid().ToString() + "_" +                  Path.GetFileName(photograph.FileName);              imagePath = @"images\" + newFileName;              photo.Relieve(@"~\" + imagePath);              imageThumbPath = @"images\thumbs\" + newFileName;             photo.Resize(width: 60, top: 60, preserveAspectRatio: true,                preventEnlarge: true);             photo.Save(@"~\" + imageThumbPath);        }     } } <!DOCTYPE html> <html> <head>   <championship>Resizing Epitome</title> </head> <trunk> <h1>Thumbnail Image</h1>   <class action="" method="mail" enctype="multipart/form-data">     <fieldset>       <legend> Creating Thumbnail Image </fable>       <label for="Paradigm">Prototype</label>       <input blazon="file" proper name="Image" />       <br/>       <input type="submit" value="Submit" />     </fieldset>   </form>     @if(imagePath != ""){     <div class="result">         <img src="@imageThumbPath" alt="Thumbnail image" />         <a href="@Html.AttributeEncode(imagePath)" target="_Self">             View total size         </a>     </div>      } </body> </html>                                  

    This code is like to the code from the previous example. The difference is that this code saves the epitome twice, once normally and once subsequently you create a thumbnail copy of the image. Start you get the uploaded image and save it in the images binder. You lot then construct a new path for the thumbnail prototype. To actually create the thumbnail, you call the WebImage helper'due south Resize method to create a 60-pixel past 60-pixel image. The instance shows how you preserve the aspect ratio and how you can forestall the image from being enlarged (in case the new size would actually make the image larger). The resized image is then saved in the thumbs subfolder.

    At the end of the markup, you lot employ the same <img> element with the dynamic src attribute that you've seen in the previous examples to conditionally testify the image. In this case, you display the thumbnail. Yous also use an <a> element to create a hyperlink to the big version of the paradigm. As with the src attribute of the <img> element, you set up the href attribute of the <a> element dynamically to whatever is in imagePath. To make sure that the path can work as a URL, y'all laissez passer imagePath to the Html.AttributeEncode method, which converts reserved characters in the path to characters that are ok in a URL.

  4. Run the page in a browser.

  5. Upload a photo and verify that the thumbnail is shown.

  6. Click the thumbnail to meet the full-size image.

  7. In the images and images/thumbs, notation that new files have been added.

Rotating and Flipping an Image

The WebImage helper besides lets yous flip and rotate images. This process shows how to get an image from the server, flip the image upside downwards (vertically), save it, then display the flipped image on the page. In this example, you're just using a file you already accept on the server (Photo2.jpg). In a real awarding, you lot'd probably flip an paradigm whose name you lot go dynamically, like you did in previous examples.

[image]

  1. Add together a new page named FlipImage.cshtml.

  2. Replace the existing content in the page with the following:

                      @{  var imagePath= "";     WebImage photo = new WebImage(@"~\Images\Photo2.jpg");     if(photo != zippo){         imagePath = @"images\Photo2.jpg";         photo.FlipVertical();         photograph.Save(@"~\" + imagePath);      } } <!DOCTYPE html> <html> <head>   <title>Go Image From File</title>   <meta http-equiv="content-blazon" content="text/html;charset=utf-8" /> </head> <body> <h1>Flip Prototype Vertically</h1> @if(imagePath != ""){   <div class="event">     <img src="@imagePath" alt="Paradigm" />   </div> } </body> </html>                                  

    The code uses the WebImage helper to get an prototype from the server. You create the path to the image using the same technique you used in earlier examples for saving images, and you lot pass that path when you create an image using WebImage:

                      WebImage photograph = new WebImage(@"~\Images\Photo2.jpg");                                  

    If an epitome is found, yous construct a new path and file proper noun, like you did in earlier examples. To flip the epitome, you telephone call the FlipVertical method, then you lot save the epitome once again.

    The paradigm is again displayed on the page by using the <img> element with the src attribute fix to imagePath.

  3. Run the page in a browser. The paradigm for Photo2.jpg is shown upside downward.

  4. Refresh the page or request the folio again to come across the image is flipped correct side up again.

To rotate an image, you lot employ the aforementioned code, except that instead of calling the FlipVertical or FlipHorizontal, you phone call RotateLeft or RotateRight.

Adding a Watermark to an Epitome

When y'all add images to your website, you lot might want to add a watermark to the image before y'all salvage it or display it on a folio. People often use watermarks to add copyright data to an image or to advertise their concern name.

[image]

  1. Add a new page named Watermark.cshtml.

  2. Replace the existing content in the page with the following:

                      @{  var imagePath= "";     WebImage photograph = new WebImage(@"~\Images\Photo3.jpg");     if(photograph != null){         imagePath = @"images\Photo3.jpg";         photograph.AddTextWatermark("My Watermark", fontColor:"Yellow", fontFamily:             "Arial");         photo.Relieve(@"~\" + imagePath);    } } <!DOCTYPE html> <html> <caput>   <title>Water Marker</title>   <meta http-equiv="content-type" content="text/html;charset=utf-8" /> </head> <body> <h1>Adding a Watermark to an Paradigm</h1> @if(imagePath != ""){   <div class="result">     <img src="@imagePath" alt="Image" />   </div> } </body> </html>                                  

    This lawmaking is like the code in the FlipImage.cshtml page from earlier (although this time it uses the Photo3.jpg file). To add together the watermark, you call the WebImage helper's AddTextWatermark method before you save the epitome. In the call to AddTextWatermark, you laissez passer the text "My Watermark", gear up the font color to yellow, and ready the font family to Arial. (Although it's non shown here, the WebImage helper besides lets you specify opacity, font family unit and font size, and the position of the watermark text.) When you salve the image it must not be read-only.

    As y'all've seen earlier, the paradigm is displayed on the page by using the <img> element with the src attribute set to @imagePath.

  3. Run the page in a browser. Notice the text "My Watermark" at the bottom-right corner of the image.

Using an Image As a Watermark

Instead of using text for a watermark, y'all can apply another paradigm. People sometimes use images like a company logo as a watermark, or they use a watermark image instead of text for copyright information.

[image]

  1. Add a new page named ImageWatermark.cshtml.

  2. Add an image to the images binder that yous can utilise as a logo, and rename the prototype MyCompanyLogo.jpg. This image should be an epitome that y'all can see conspicuously when it's set to 80 pixels wide and 20 pixels high.

  3. Replace the existing content in the page with the following:

                      @{  var imagePath = "";    WebImage WatermarkPhoto = new WebImage(@"~\" +         @"\Images\MyCompanyLogo.jpg");     WebImage photo = new WebImage(@"~\Images\Photo4.jpg");     if(photo != null){         imagePath = @"images\Photo4.jpg";         photo.AddImageWatermark(WatermarkPhoto, width: 80, pinnacle: 20,            horizontalAlign:"Eye", verticalAlign:"Bottom",            opacity:100,  padding:10);       photograph.Salve(@"~\" + imagePath);    } } <!DOCTYPE html> <html> <head>   <championship>Epitome Watermark</championship>   <meta http-equiv="content-type" content="text/html;charset=utf-eight" /> </caput> <body>   <h1>Using an Image every bit a Watermark</h1>   @if(imagePath != ""){     <div class="consequence">       <img src="@imagePath" alt="Image" />     </div>   } </body> </html>                                  

    This is another variation on the code from earlier examples. In this case, yous call AddImageWatermark to add together the watermark image to the target image (Photo3.jpg) before you save the paradigm. When you lot call AddImageWatermark, you set its width to 80 pixels and the height to twenty pixels. The MyCompanyLogo.jpg prototype is horizontally aligned in the centre and vertically aligned at the bottom of the target prototype. The opacity is prepare to 100% and the padding is fix to 10 pixels. If the watermark image is bigger than the target image, nothing will happen. If the watermark paradigm is bigger than the target epitome and you gear up the padding for the image watermark to zero, the watermark is ignored.

    As earlier, you brandish the image using the <img> element and a dynamic src attribute.

  4. Run the page in a browser. Discover that the watermark image appears at the bottom of the main image.

Additional Resources

Working with Files in an ASP.NET Web Pages Site

Introduction to ASP.NET Web Pages Programming Using the Razor Syntax