如何调整HttpPostedFileWrapper的大小?

时间:2012-06-14 06:46:12

标签: c# asp.net-mvc image

我需要按比例调整此图像的大小为411px。 怎么做?

[HttpPost]
        public WrappedJsonResult UploadImage(HttpPostedFileWrapper imageFile, int id)
        {
            if (imageFile == null || imageFile.ContentLength == 0)
            {
                return new WrappedJsonResult
                {
                    Data = new
                    {
                        IsValid = false,
                        Message = "No file was uploaded.",
                        ImagePath = string.Empty
                    }
                };
            }

            var fileName = String.Format("{0}_{1}.jpg", id, Guid.NewGuid().ToString());
            var imagePath = Path.Combine(Server.MapPath(Url.Content("~/Content/UploadPhoto")), fileName);

            imageFile.SaveAs(imagePath);
}

1 个答案:

答案 0 :(得分:0)

public ActionResult UploadImage(HttpPostedFileBase imageFile, int id)
{
    if (imageFile == null || imageFile.ContentLength == 0)
    {
        return new WrappedJsonResult
        {
            Data = new
            {
                IsValid = false,
                Message = "No file was uploaded.",
                ImagePath = string.Empty
            }
        };
    }

    var fileName = String.Format("{0}_{1}.jpg", id, Guid.NewGuid().ToString());
    var imagePath = Path.Combine(Server.MapPath(Url.Content("~/Content/UploadPhoto")), fileName);

    using (var input = new Bitmap(imageFile.InputStream))
    {
        int width;
        int height;
        if (input.Width > input.Height)
        {
            width = 411;
            height = 411 * input.Height / input.Width;
        }
        else
        {
            height = 411;
            width = 411 * input.Width / input.Height;
        }

        using (var thumb = new Bitmap(width, height))
        using (var graphic = Graphics.FromImage(thumb))
        {
            graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
            graphic.SmoothingMode = SmoothingMode.AntiAlias;
            graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;

            graphic.DrawImage(input, 0, 0, width, height);
            using (var output = System.IO.File.Create(imagePath))
            {
                thumb.Save(output, ImageFormat.Jpeg);
            }
        }
    }

    ...
}

顺便提一下,您会注意到我已在动作签名中将HttpPostedFileWrapper替换为HttpPostedFileBase,因为这是要使用的正确类型。