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



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

我使用一个名为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);
     }
}

看看他们的网站,有几个示例可以完成。 我希望这对:)有所帮助

相关内容

最新更新