1

所以我有一个处理文件上传的动作。我要做的是检查文件大小是否为 100kb,如果不是,我将其调整为一定的宽度和高度(尽管我不确定这是达到所需大小的正确方法,想法?)

然后我打算将它保存到我网站的子域中。

这就是动作的样子

public ActionResult New(string account, int id, HttpPostedFileBase file)
        {
            if (file == null)
            {
                ModelState.AddModelError("", "File not found.");
                return View();
            }

            if (!ImageUpload.FileTypeValid(file.ContentType))
            {
                ModelState.AddModelError("", "File type is invalid. Please choose a different file.");
                return View();
            }

            if (file.ContentLength > 100)
            {
                Image image = ImageUpload.ResizeFile(file, 100, 100);
            }

            try
            {

                icdb.SaveChanges();
                ModelState.AddModelError("", "Sucesfully saved Image.");
                return RedirectToAction("Details", "OfAController", new { account = account, id= id});
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
            }

            return View();
        }

这是调整大小的方法

static public Image ResizeFile(HttpPostedFileBase file, int targeWidth, int targetHeight)
        {
            Image originalImage = Image.FromStream(file.InputStream, true, true);
            var newImage = new MemoryStream();
            Rectangle origRect = new Rectangle(0, 0, originalImage.Width, originalImage.Height);
            // if targets are null, require scale. for specified sized images eg. Event Image, or Profile photos.
            int newWidth = targeWidth;
            int newHeight = targetHeight;
            var bitmap = new Bitmap(newWidth, newHeight);

            try
            {
                using (Graphics g = Graphics.FromImage(bitmap))
                {
                    g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
                    g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    g.DrawImage(originalImage, new Rectangle(0, 0, newWidth, newHeight), origRect, GraphicsUnit.Pixel);
                    bitmap.Save(newImage, originalImage.RawFormat);
                }
                return (Image)bitmap;
            }
            catch
            {   // error before IDisposable ownership transfer
                if (bitmap != null)
                    bitmap.Dispose();
                throw new Exception("Error resizing file.");
            }
        }

所以我的问题是,我试图找到如何将这个调整大小的文件保存到我的目录的方法。然后我一直发现我必须先上传图片才能调整大小?那正确吗?或者有没有办法在我保存到我的目录之前调整它的大小?

想法?

谢谢!

4

0 回答 0