MVC3.0 上传图片并生成缩略图

转自:http://mikelai.blog.163.com/blog/static/18411126620118771732675/

Controller:
public ActionResult Upload()
{
return View();
}
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
var ostream = file.InputStream;
var orimage = Image.FromStream(ostream);
int owidth = orimage.Width; //原图宽度
int oheight = orimage.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 objimage = new Bitmap(objwidth, objheight);
Graphics graphics = Graphics.FromImage(objimage);
graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; //设置高质量插值法
graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;//设置高质量,低速度呈现平滑程度
graphics.Clear(Color.Transparent); //清空画布并以透明背景色填充
graphics.DrawImage(orimage, new Rectangle(0, 0, objwidth, objheight), new Rectangle(0, 0, owidth, oheight), GraphicsUnit.Pixel);
 
//rewrite imagename
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 objfilePath= Path.Combine(HttpContext.Server.MapPath("/content/videos"), Path.GetFileName(objname));
try
{
file.SaveAs(orifilePath);
objimage.Save(objfilePath, System.Drawing.Imaging.ImageFormat.Png);
}
 
catch (Exception ex)
{
throw ex;
}
finally
{
//释放资源
orimage.Dispose();
graphics.Dispose();
objimage.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" />
}
 
 
上一篇:Oracle 数据库语句大全


下一篇:C++中 vector(容器)的用法