In this article, we will learn how to create thumbnails of images while uploading the images in ASP.NET MVC. The concept is the same for ASP.NET too. It is very important to create thumbnails of images of different sizes, depending upon the scenario and type of application. If we create a thumbnail of an image, it reduces the image byte size along with its dimension, resulting in a fast processing of page.
If we create a thumbnail of a 1500 KB image file, the thumbnail’s size would be less than 50 KB. .NET provides image class and its one method can create a thumbnail too, but reducing the dimension of the image with its ratio is very important.
The main advantage of using thumbnails is the improvement in application performance beacuse they load faster and process quickly. So, let's start.
Create an MVC Project
Step 1 : Open Visual Studio.
Step 2 : Go to File => New Project.
- Select Visual C# => Web => ASP.NET Web Application.
- Name your solution (eg. EasyCRM) and Project (EasyCRM.UI); then, click OK.
- Select MVC.
- Change authentication to "Individual Accounts".
Now, you will see the following screen.
Creating Image Handler
Step 1: Create a new folder called ImageHandler.
Step 2: Add a new class called UploadImage.
Step 3: Add a function called "Crop" with parameters described below.
S.No | Type | Description |
Width | int | New width of Image |
Height | int | New Height of Image |
streamIMg | Stream | Image Stream |
SaveFilePath | string | Path of server where file is saved. (Eg. "~/Upload/Images/thumb") |
Step 4
Add the following lines of code to the "Crop" method.
- public class UploadImage
- {
- public static void Crop(int Width, int Height, Stream streamImg, string saveFilePath)
- {
- Bitmap sourceImage = new Bitmap(streamImg);
- using(Bitmap objBitmap = new Bitmap(Width, Height))
- {
- objBitmap.SetResolution(sourceImage.HorizontalResolution, sourceImage.VerticalResolution);
- using(Graphics objGraphics = Graphics.FromImage(objBitmap))
- {
-
- objGraphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
- objGraphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
- objGraphics.DrawImage(sourceImage, 0, 0, Width, Height);
-
- objBitmap.Save(saveFilePath);
- }
- }
- }
- }
UploadImage classs looks like this in Solution Explorer.
So far, we have created a method to resize and save the image.
Now, let's build a Controller which will help to,
- display a form to upload images.
- upload selected images to the "Upload" folder.
Adding Controller
Step 1
Add a Controller called Manage_Gallery.
Step 2
Add a method called AddPhotoGallery().
- public ActionResult AddPhotoGallery() {
- return View();
- }
Step 3
Add a View for this method (For now, I am creating an empty View).
Step 4
Let's add the following lines of code in View.
- @ {
- ViewBag.Title = "Add Photo Gallery";
- Layout = "~/Views/Shared/_LayoutAdminPanel.cshtml";
- }
- <h2> Add Photo Gallery </h2>
-
- @ * @using(Html.BeginForm("Method_Name", "Controller_Name", FormMethod(Post / GET), new {
- enctype = "multipart/form-data", area = "Area_Name"
- })) * @
- @using(Html.BeginForm("AddPhotoGallery", "Manage_Gallery", FormMethod.Post, new {
- enctype = "multipart/form-data", area = "SuperAdmin"
- }))
- {
- @Html.AntiForgeryToken() < div class = "form-orizontal" > <h4 > Create New Image Gallery </h4>
- <hr />
- @Html.ValidationSummary(true, "", new {@class = "text-danger"})
- <div class="form-group">
- <div class="col-md-2"> Select Images </div>
- <div class="col-md-10">
- <input type ="file" name="Images" value="Select Images" id="Images" multiple />
- </div>
- </div>
- <div class = "form-group">
- <div class = "col-md-offset-2 col-md-10" >
- <input type = "submit" value = "Save" class = "btn btn-success" />
- </div>
- </div>
- </div>
-
- }
- @section Scripts {
- @Scripts.Render("~/bundles/jqueryval")
- }
Step 5
Now, add a method called AddPhotoGallery on the same Controller (Don't forget to mention the method as Post type, by adding [HttpPost]).
Add the following lines of code. Your method should look like below.
-
-
-
-
-
- [HttpPost]
- public ActionResult AddPhotoGallery(IEnumerable <HttpPostedFileBase> Images)
- {
- try
- {
- foreach(var image in Images) {
- if (image != null)
- {
- string fileName = Guid.NewGuid().ToString() + Path.GetExtension(image.FileName);
- var path = Path.Combine(Server.MapPath("~/Upload/Images/"), fileName);
- image.SaveAs(path);
- UploadImage.Crop(320, 240, image.InputStream, Path.Combine(Server.MapPath("~/Upload/Images/thumb/") + fileName));
- }
- }
- TempData["MessageValue"] = "1";
- TempData["Message"] = "Image Gallery added successfully";
- }
- catch
- {
- TempData["MessageValue"] = "0";
- TempData["Message"] = "Error occured while adding Image Galley";
- }
- return RedirectToAction("Index", "Manage_Gallery", new {area = "SuperAdmin" });
- }
Step 6
Now, run the application. You will be able to see the following screen.
Step 7
Now, select an image and upload it.
You will be able to see the uploaded images and thumbnail images in "Images" and "thumb" folder respectively.
Note
Don't forget to add Upload Folder in Project. Also add Images folder inside Upload folder. Add thumb folder inside Images Folder as below.
If you have any queries, please feel free to comment.
I hope now you will be able to write your own codes for creating thumbnails of images and upload images in C#.
You may also like