为上传的图像创建缩略图

Create Thumbnails for Uploaded Images

我有一个 asp.net mvc 应用程序,我可以在其中一次上传多张图片并且工作正常,但我在使用原始图片创建缩略图时遇到问题。

代码如下:

[HttpPost]
        public ActionResult SaveUploadedFile()
        {
            bool isSavedSuccessfully = true;
            string fName = "";

            try
            {
                foreach (string fileName in Request.Files)
                {
                    HttpPostedFileBase file = Request.Files[fileName];

                    fName = file.FileName;

                    if (file != null && file.ContentLength > 0)
                    {
                        var originalDirectory = new DirectoryInfo(string.Format("{0}Images", Server.MapPath(@"\")));

                        string pathString = Path.Combine(originalDirectory.ToString(), "Gallery");
                        string pathString2 = Path.Combine(originalDirectory.ToString(), "Gallery\Thumbs");

                        //var fileName1 = Path.GetFileName(file.FileName);

                        bool exists = Directory.Exists(pathString);
                        bool exists2 = Directory.Exists(pathString2);

                        if (!exists)
                            Directory.CreateDirectory(pathString);

                        if (!exists2)
                            Directory.CreateDirectory(pathString2);

                        var path = string.Format("{0}\{1}", pathString, file.FileName);

                        file.SaveAs(path);

                        //WebImage img = new WebImage(file.InputStream);
                        WebImage img = new WebImage(fileName);
                        //if (img.Width > 1000)
                        img.Resize(100, 100);
                        img.Save(pathString2);

                    }

                }

            }
            catch (Exception ex)
            {
                isSavedSuccessfully = false;
            }

            if (isSavedSuccessfully)
            {
                return Json(new { Message = fName });
            }
            else
            {
                return Json(new { Message = "Error in saving file" });
            }
        }

所以基本上 file.SaveAs(path); 是最后一行,我实际上保存了图像,但在该行之后我尝试创建并保存拇指,但它不起作用(我确实得到了 Thumbs 之前创建的文件夹)。

我也得到了 Error in saving file 响应,但那是因为我正在尝试创建和保存拇指,如果我删除它,我就不会得到它,而且我不知道如何 return实际错误实际看错误是什么。

答案是这样的:

var path2 = string.Format("{0}\{1}", pathString2, file.FileName)

WebImage img = new WebImage(file.InputStream);
img.Resize(250, 250);
img.Save(path2);