为上传的图片创建缩略图

本文关键字:创建 略图 | 更新日期: 2023-09-27 18:16:36

我有一个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响应,但那是因为我试图创建和保存拇指,如果我删除,然后我不得到它,我不知道如何返回实际的错误,实际看看错误是什么。

为上传的图片创建缩略图

答案是:

var path2 = string.Format("{0}''{1}", pathString2, file.FileName)
WebImage img = new WebImage(file.InputStream);
img.Resize(250, 250);
img.Save(path2);