ASP.NET上传图像,调整大小并保存到文件系统。

时间:2012-10-09 03:36:08

标签: c# asp.net

尝试使用FileUpload对话框上传图像时,我没有运气,在保持纵横比的同时调整大小,然后使用c#和ASP.NET将其保存到我的文件系统 有没有人有一个可行的解决方案或某个可以向我展示工作示例的链接?我看过和尝试的很多解决方案只适用于C#而不适用于ASP.NET

1 个答案:

答案 0 :(得分:0)

ImageResizer将为您提供所需的一切:

http://imageresizing.net/

string fileExt = System.IO.Path.GetExtension(imageUpload.FileName);
if (string.Equals(fileExt, ".jpg", StringComparison.OrdinalIgnoreCase))
{
    foreach (string fileKey in HttpContext.Current.Request.Files.Keys)
    {
        HttpPostedFile file = HttpContext.Current.Request.Files[fileKey];
        if (file.ContentLength <= 0) continue; //Skip unused file controls.

        try
        {
             ImageJob i = new ImageJob(file, "~/eventimages/<guid>_<filename:A-Za-z0-9>.<ext>",
                 new ResizeSettings("width=60&height=60&format=jpg&crop=auto"));
             i.Build();

             ImageJob j = new ImageJob(file, "~/eventimages/<guid>_<filename:A-Za-z0-9>.<ext>",
                 new ResizeSettings("width=250&height=250&format=jpg&crop=auto"));
             j.Build();

             string sitePath = MapPath(@"~");
             thumbImagePath = i.FinalPath.Replace(sitePath, "~\\");
             mainImagePath = j.FinalPath.Replace(sitePath, "~\\");
         }
         catch
         {
  // Had to swallow the exception here: 
  // http://stackoverflow.com/questions/7533845/system-argumentexception-parameter-is-not-valid
         }
     }
  }