user1387089
user1387089

Reputation: 19

Convert that image in thumbnail and save both the images in asp.net-mvc3

upload image by upload control and convert that image in thumbnail and save both file actual image in image folder and thumbnail image in thumbnail Image folder in asp.net-mvc3

Upvotes: 1

Views: 594

Answers (1)

Brendan Vogt
Brendan Vogt

Reputation: 26038

I use a 3rd party library called Image Resizer. I struggled with the uploading of images and retaining quality, this library helped me out alot.

In your view:

@model YourProject.ViewModels.ProductImageUploadCreateViewModel
@using (Html.BeginForm("Upload", "ProductImage", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
     <input type="file" name="ImageFile1" id="ImageFile1">
}

Your controller:

public class ProductImageController : Controller
{
     [HttpPost]
     public ActionResult Upload(ProductImageUploadCreateViewModel viewModel)
     {
          if (!ModelState.IsValid)
          {
               return View(viewModel);
          }

          if (viewModel.ImageFile1 != null)
          {
               UploadImage(viewModel.ProductId, "1", viewModel.ImageFile1);
          }

          // Return to where ever...
     }
}

Your upload method:

private void UploadImage(int productId, string imageNo, HttpPostedFileBase imageFile)
{
     string uploadPath = Server.MapPath("~/Assets/Images/Products/" + productId);
     if (!Directory.Exists(uploadPath))
     {
          Directory.CreateDirectory(uploadPath);
     }

     Dictionary<string, string> versions = new Dictionary<string, string>();
     versions.Add("_m", "width=150&height=150&scale=both&format=jpg");  // Medium size

     string filePrefix = productId + "_" + imageNo;
     versions.Add("_s", "width=90&height=90&scale=both&format=jpg");  // Small size
     versions.Add("_l", "width=300&height=300&scale=both&format=jpg");  // Large size

     foreach (string fileSuffix in versions.Keys)
     {
          // Generate a filename
          string fileName = Path.Combine(uploadPath, filePrefix + fileSuffix);

          // Let the image builder add the correct extension based on the output file type
          fileName = ImageBuilder.Current.Build(imageFile, fileName, new ResizeSettings(versions[fileSuffix]), false, true);
     }
}

Have a look on their website, there are a couple of samples that you can work through. I hope this helps :)

Upvotes: 1

Related Questions