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 objfile Path= Path.Combine(HttpContext.Server.MapPath("/content/videos"), Path.GetFileName(objname));
try
{
file.SaveAs( orifile Path);
objimage.Save( objfile Path, 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" />
}
 
 

转载于:https://www.cnblogs.com/heifengwll/p/3473276.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值