2012-05-11 12 views
1

アップロード制御で画像をアップロードし、その画像をサムネイルに変換し、画像フォルダ内の実際の画像とサムネイル画像をサムネイルに保存asp.netの画像フォルダ-mvc3その画像をサムネイルに変換し、両方の画像をasp.net-mvc3に保存する

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

が自分のウェブサイト上で見てください、そのサンプルがいくつかありますあなたは働くことができます。私はこれが助けてくれることを願っています:)

関連する問題