您的位置:首页 > 编程语言 > ASP

ASP.NET MVC 网站开发总结(三) ——图片截图上传

2016-04-29 21:15 741 查看
本着简洁直接,我们就直奔主题吧,这里需要使用到一个网页在线截图插件imgareaselect(请自行下载)。

前台页面:

//更新用户头像
[HttpPost]
public ActionResult UpdatePicture(int x1, int y1, int x2, int y2, HttpPostedFileBase pictureFile)
{
if (pictureFile != null && pictureFile.ContentLength > 0)
{
if (pictureFile.ContentLength > 5242880)
{
return Content("<script>alert('错误提示:文件大小超出指定范围!');</script>");
}
string fileName = pictureFile.FileName.Split('\\').Last();
string fileExt = fileName.Substring(fileName.LastIndexOf('.')).ToLower();
if (fileExt == ".jpg" || fileExt == ".png")
{
string path = Server.MapPath("~/Resources/HeadPicture");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
fileName = DateTime.Now.ToFileTime().ToString() + Guid.NewGuid().ToString("N") + fileExt;
var picPath = Path.Combine(path, fileName);
pictureFile.SaveAs(picPath);//从客户端保存文件到本地

//检查裁剪图片是否合法并裁剪图片
var image = new WebImage(picPath);
double height = image.Height;
double width = image.Width;
if (width > height)
{
height = (int)(280 * (height / width));
width = 280;
}
else
{
width = (int)(280 * (width / height));
height = 280;
}
image.Resize((int)width, (int)height);//调整图片大小

var length = x2 - x1;
if (x1 >= 0 && x1 <= 280 && y1 >= 0 && y1 <= 280 && length >= 50 && length <= 280 && x1 + length <= width && y1 + length <= height)
{
image.Crop(y1, x1, (int)(height - y1 - length), (int)(width - x1 - length));
image.Save(picPath);
var logined = entity.Users.Find(Convert.ToInt32(User.Identity.Name));
logined.Picture = fileName;
entity.SaveChanges();
return Content("<script>alert('操作成功提示:成功更新照片!');</script>");
}
else
{
System.IO.File.Delete(picPath);
return Content("<script>alert('错误提示:上传的图片信息不合法!');</script>");

}
}
else
{
return Content("<script>alert('错误提示:上传的文件格式不正确!');</script>");
}
}
else
{
return Content("<script>alert('错误提示:上传的文件是空文件!');</script>");
}
}


View Code
上面代码是一个用户头像更新的代码,也是先将图片等比例放缩(长或宽放缩为280px),也前台页面上面的图片相对应,然后再进行裁剪。

第一次团队合作ASP.NET MVC 网站开发总结就到这里吧。

<我的博客主页>:http://www.cnblogs.com/forcheng/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: