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

by Tom FitzMacken

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

What y'all'll larn:

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

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

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

Software versions used in the tutorial

  • ASP.NET Spider web Pages (Razor) 2
  • WebMatrix 2

This tutorial also works with WebMatrix 3.

Adding an Image to a Web Folio Dynamically

You can add images to your website and to individual pages while yous're developing the website. You lot tin likewise allow users upload images, which might exist useful for tasks similar letting them add together a profile photo.

If an epitome is already available on your site and you just desire to display it on a folio, y'all apply an HTML <img> element like this:

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

Sometimes, though, you need to be able to display images dynamically — that is, you don't know what image to brandish until the page is running.

The process in this department shows how to display an image on the fly where users specify the image file name from a list of epitome names. They select the name of the image from a drop-down list, and when they submit the page, the image they selected is displayed.

[image]

  1. In WebMatrix, create a new website.

  2. Add a new folio named DynamicImage.cshtml.

  3. In the root folder of the website, add a new binder and name it images.

  4. Add iv images to the images binder y'all just created. (Whatsoever images yous have handy will practice, but they should fit onto a page.) Rename the images Photo1.jpg, Photo2.jpg, Photo3.jpg, and Photo4.jpg. (You won't use Photo4.jpg in this procedure, only you'll use it later in the article.)

  5. Verify that the 4 images are not marked as read-only.

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

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

    The body of the page has a drop-down list (a <select> element) that's named photoChoice. The listing has three options, and the value attribute of each list pick has the name of one of the images that yous put in the images folder. Essentially, the list lets the user select a friendly proper noun like "Photo 1", and it so passes the .jpg file proper noun when the page is submitted.

    In the lawmaking, you lot can become the user's selection (in other words, the image file name) from the list by reading Asking["photoChoice"]. You first run into if there's a selection at all. If there is, yous construct a path for the prototype that consists of the proper noun of the folder for the images and the user's image file name. (If you tried to construct a path but there was goose egg in Request["photoChoice"], you'd get an error.) This results in a relative path like this:

    images/Photo1.jpg

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

    In the body, in that location'south also an <img> element that's used to display the epitome that the user picked. The src attribute isn't ready to a file proper noun or URL, like you'd practice to display a static element. Instead, information technology's set to @imagePath, meaning that information technology gets its value from the path you lot prepare in lawmaking.

    The first time that the page runs, though, at that place's no image to display, considering the user hasn't selected anything. This would normally mean that the src aspect would exist empty and the epitome would show up as a ruby-red "10" (or whatever the browser renders when it can't find an paradigm). To prevent this, you put the <img> element in an if cake that tests to encounter whether the imagePath variable has anything in it. If the user fabricated a selection, imagePath contains the path. If the user didn't pick an image or if this is the get-go fourth dimension the page is displayed, the <img> element isn't even rendered.

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

  8. Select an image from the drop-downwards list and then click Sample Image. Make sure that yous see different images for different choices.

Uploading an Image

The previous example showed you how to display an image dynamically, but information technology worked only with images that were already on your website. This procedure shows how to allow users upload an image, which is then displayed on the folio. In ASP.Net, y'all tin manipulate images on the fly using the WebImage helper, which has methods that let y'all create, dispense, and save images. The WebImage helper supports all the common web image file types, including .jpg, .png, and .bmp. Throughout this article, you lot'll apply .jpg images, but y'all can use any of the image types.

[image]

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

  2. Supersede the existing content in the page with the post-obit:

                      @{  WebImage photograph = null;     var newFileName = "";     var imagePath = "";      if(IsPost){         photo = WebImage.GetImageFromRequest();         if(photograph != null){             newFileName = Guid.NewGuid().ToString() + "_" +                 Path.GetFileName(photo.FileName);             imagePath = @"images\" + newFileName;              photo.Save(@"~\" + imagePath);         }     } } <!DOCTYPE html> <html> <caput>   <title>Prototype Upload</championship> </head> <trunk>   <grade action="" method="mail service" enctype="multipart/form-data">     <fieldset>       <fable> Upload Prototype </legend>       <characterization for="Image">Prototype</label>       <input type="file" proper noun="Image" />       <br/>       <input blazon="submit" value="Upload" />     </fieldset>   </form>   <h1>Uploaded Paradigm</h1>     @if(imagePath != ""){     <div class="result">         <img src="@imagePath" alt="image" />      </div>     } </torso> </html>                                  

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

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

    A lot of the piece of work in this example involves getting and setting file and path names. The effect is that you want to get the proper name (and just the name) of the paradigm that the user uploaded, and then create a new path for where you're going to store the paradigm. Considering users could potentially upload multiple images that accept the same name, y'all use a fleck of extra code to create unique names and make sure that users don't overwrite existing pictures.

    If an paradigm really has been uploaded (the test if (photo != null)), you lot go the prototype proper noun from the image's FileName belongings. When the user uploads the paradigm, FileName contains the user'due south original proper name, which includes the path from the user's computer. It might look like this:

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

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

                      Path.GetFileName(photo.FileName)                                  

    You then create a new unique file proper noun by calculation a GUID to the original proper name. (For more about GUIDs, meet About GUIDs later in this commodity.) So you construct a complete path that you can utilise to save the image. The save path is made upwards of the new file name, the folder (images), and the electric current website location.

    Note

    In order for your code to save files in the images folder, the awarding needs read-write permissions for that binder. On your evolution computer this is not typically an issue. Nonetheless, when you publish your site to a hosting provider's web server, you might need to explicitly set those permissions. If you lot run this code on a hosting provider'southward server and get errors, check with the hosting provider to find out how to set those permissions.

    Finally, you pass the salve path to the Save method of the WebImage helper. This stores the uploaded image under its new name. The save method looks like this: photograph.Relieve(@"~\" + imagePath). The complete path is appended to @"~\", which is the current website location. (For information virtually the ~ operator, meet Introduction to ASP.Cyberspace Web Programming Using the Razor Syntax.)

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

  3. Run the page in a browser.

  4. Upload an prototype and make sure information technology'south displayed in the page.

  5. In your site, open the images binder. You lot see that a new file has been added whose file proper noun looks something like this::

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

    This is the prototype that you uploaded with a GUID prefixed to the name. (Your own file will have a dissimilar 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 eight-iv-four-4-12 characters. (Technically, a GUID is a 16-byte/128-bit number.) When yous need a GUID, yous can call specialized code that generates a GUID for you. The thought behind GUIDs is that between the enormous size of the number (iii.4 10 1038) and the algorithm for generating it, the resulting number is near guaranteed to be one of a kind. GUIDs therefore are a good way to generate names for things when you must guarantee that yous won't employ the same name twice. The downside, of grade, is that GUIDs aren't specially user friendly, so they tend to be used when the name is used only in code.

Resizing an Epitome

If your website accepts images from a user, you might want to resize the images before yous display or salve them. You tin can again apply the WebImage helper for this.

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

[image]

  1. Add together a new folio named Thumbnail.cshtml.

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

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

                      @{       WebImage photo = null;     var newFileName = "";     var imagePath = "";     var imageThumbPath  = "";      if(IsPost){         photo = WebImage.GetImageFromRequest();         if(photograph != zero){              newFileName = Guid.NewGuid().ToString() + "_" +                  Path.GetFileName(photo.FileName);              imagePath = @"images\" + newFileName;              photo.Save(@"~\" + imagePath);              imageThumbPath = @"images\thumbs\" + newFileName;             photo.Resize(width: threescore, height: 60, preserveAspectRatio: true,                preventEnlarge: truthful);             photograph.Save(@"~\" + imageThumbPath);        }     } } <!DOCTYPE html> <html> <head>   <title>Resizing Prototype</championship> </caput> <body> <h1>Thumbnail Image</h1>   <class activity="" method="mail service" enctype="multipart/form-data">     <fieldset>       <legend> Creating Thumbnail Prototype </fable>       <label for="Image">Image</label>       <input type="file" proper noun="Epitome" />       <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 full size         </a>     </div>      } </body> </html>                                  

    This lawmaking is similar to the code from the previous example. The difference is that this code saves the image twice, one time normally and once later you create a thumbnail copy of the prototype. Starting time you become the uploaded epitome and salve information technology in the images binder. You lot and so construct a new path for the thumbnail image. To actually create the thumbnail, you call the WebImage helper's Resize method to create a 60-pixel by 60-pixel image. The example shows how y'all preserve the attribute ratio and how you can forbid the image from beingness 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 use the aforementioned <img> element with the dynamic src attribute that you've seen in the previous examples to conditionally show the image. In this case, yous display the thumbnail. Y'all as well apply an <a> element to create a hyperlink to the big version of the prototype. As with the src attribute of the <img> element, you set the href aspect of the <a> chemical element dynamically to whatever is in imagePath. To make sure that the path can work as a URL, you pass 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 see the full-size image.

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

Rotating and Flipping an Image

The WebImage helper as well lets you flip and rotate images. This process shows how to get an image from the server, flip the paradigm upside downward (vertically), save information technology, and then display the flipped image on the page. In this example, you're just using a file yous already take on the server (Photo2.jpg). In a real application, you'd probably flip an image whose proper name y'all get dynamically, like yous 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(photograph != zilch){         imagePath = @"images\Photo2.jpg";         photo.FlipVertical();         photo.Salve(@"~\" + imagePath);      } } <!DOCTYPE html> <html> <head>   <title>Get Image From File</championship>   <meta http-equiv="content-type" content="text/html;charset=utf-eight" /> </head> <body> <h1>Flip Image Vertically</h1> @if(imagePath != ""){   <div class="result">     <img src="@imagePath" alt="Prototype" />   </div> } </torso> </html>                                  

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

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

    If an prototype is constitute, you construct a new path and file name, like you did in earlier examples. To flip the image, you call the FlipVertical method, and then yous save the image once more.

    The image is again displayed on the folio by using the <img> element with the src attribute set to imagePath.

  3. Run the folio in a browser. The image for Photo2.jpg is shown upside down.

  4. Refresh the folio or request the page once more to encounter the prototype is flipped right side up once again.

To rotate an image, yous utilize the same lawmaking, except that instead of calling the FlipVertical or FlipHorizontal, you call RotateLeft or RotateRight.

Calculation a Watermark to an Image

When y'all add images to your website, you lot might desire to add a watermark to the image before you relieve information technology or brandish it on a page. People often use watermarks to add copyright data to an image or to advertise their business name.

[image]

  1. Add together a new folio named Watermark.cshtml.

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

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

    This lawmaking is similar the code in the FlipImage.cshtml folio from earlier (although this time it uses the Photo3.jpg file). To add the watermark, you call the WebImage helper's AddTextWatermark method earlier you salve the image. In the call to AddTextWatermark, y'all laissez passer the text "My Watermark", set the font color to yellow, and fix the font family to Arial. (Although it's non shown here, the WebImage helper also lets y'all specify opacity, font family and font size, and the position of the watermark text.) When y'all save the image it must non exist read-only.

    As you've seen before, the image is displayed on the page by using the <img> chemical element with the src attribute gear up to @imagePath.

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

Using an Image As a Watermark

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

[image]

  1. Add a new folio named ImageWatermark.cshtml.

  2. Add an image to the images folder that y'all tin employ as a logo, and rename the image MyCompanyLogo.jpg. This image should be an prototype that you lot can come across conspicuously when it's set to 80 pixels wide and 20 pixels high.

  3. Replace the existing content in the page with the post-obit:

                      @{  var imagePath = "";    WebImage WatermarkPhoto = new WebImage(@"~\" +         @"\Images\MyCompanyLogo.jpg");     WebImage photo = new WebImage(@"~\Images\Photo4.jpg");     if(photo != nothing){         imagePath = @"images\Photo4.jpg";         photograph.AddImageWatermark(WatermarkPhoto, width: eighty, height: 20,            horizontalAlign:"Center", verticalAlign:"Lesser",            opacity:100,  padding:10);       photo.Salve(@"~\" + imagePath);    } } <!DOCTYPE html> <html> <head>   <championship>Image Watermark</title>   <meta http-equiv="content-type" content="text/html;charset=utf-viii" /> </caput> <torso>   <h1>Using an Prototype as a Watermark</h1>   @if(imagePath != ""){     <div class="result">       <img src="@imagePath" alt="Epitome" />     </div>   } </body> </html>                                  

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

    As before, you display the paradigm using the <img> element and a dynamic src attribute.

  4. Run the page in a browser. Find that the watermark paradigm 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