Controller:
public ActionResult Upload()
{
return View();
}
[HttpPost]
public ActionResult Upload(
HttpPostedFileBase file)
{
var ostream = file.InputStream;
var orp_w_picpath = Image.FromStream(ostream);
int owidth = orp_w_picpath.Width; //原图宽度
int oheight = orp_w_picpath.Height; //原图高度
int objwidth = 100; //设置缩略图初始宽度
int objheight = 100; //设置缩略图初始高度
//按比例计算出缩略图的宽度和高度
if (owidth >= oheight)
{
objheight = (int)Math.Floor(Convert.ToDouble(oheight) * (Convert.ToDouble(objwidth) / Convert.ToDouble(owidth)));
}
else
{
objwidth = (int)Math.Floor(Convert.ToDouble(owidth) * (Convert.ToDouble(objheight) / Convert.ToDouble(oheight)));
}
Bitmap objp_w_picpath = new Bitmap(objwidth, objheight);
Graphics graphics = Graphics.FromImage(objp_w_picpath);
graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; //设置高质量插值法
graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;//设置高质量,低速度呈现平滑程度
graphics.Clear(Color.Transparent); //清空画布并以透明背景色填充
graphics.DrawImage(orp_w_picpath, new Rectangle(0, 0, objwidth, objheight), new Rectangle(0, 0, owidth, oheight), GraphicsUnit.Pixel);
//rewrite p_w_picpathname
var extensionName = Path.GetExtension(file.FileName);
var oriname = "ori" + DateTime.Now.ToString("yyyyMMddHHmmss") + extensionName;
var objname = "obj" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".png";
var
orifilePath = Path.Combine(HttpContext.Server.MapPath("/content/videos"), Path.GetFileName(oriname));
var
objfile
Path
= Path.Combine(HttpContext.Server.MapPath("/content/videos"), Path.GetFileName(objname));
try
{
file.SaveAs(
orifile
Path);
objp_w_picpath.Save(
objfile
Path, System.Drawing.Imaging.ImageFormat.Png);
}
catch (Exception ex)
{
throw ex;
}
finally
{
//释放资源
orp_w_picpath.Dispose();
graphics.Dispose();
objp_w_picpath.Dispose();
}
return RedirectToAction("Index");
}
View:
@using (Html.BeginForm("Upload", "Admin", FormMethod.Post, new {
enctype = "multipart/form-data" }))
{
<label>
Filename:
</label>
<input type="file" name="file" />
<input type="submit" value="Submit" />
}
转载于:https://blog.51cto.com/kebin/664441