在缩略图中转换该图像并将图像保存在asp.net-mvc3中

时间:2012-05-11 11:21:56

标签: asp.net-mvc-3 image file-upload

通过上传控件上传图片并将图片转换为缩略图,并将图片文件夹中的文件实际图片和缩略图图片保存在asp.net-mvc3缩略图图片文件夹中

1 个答案:

答案 0 :(得分:1)

我使用名为Image Resizer的第三方库。我努力上传图像并保持质量,这个图书馆帮了我很多。

在您看来:

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

你的控制器:

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...
     }
}

您的上传方式:

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);
     }
}

在他们的网站上看看,有几个样本可以解决。我希望这会有所帮助:)