MVC使用JCrop上传、裁剪图片
JCrop用来裁剪图片,本篇想体验的是:
在视图页上传图片:

上传成功,跳转到另外一个编辑视图页,使用JCrop对该图片裁剪,并保存图片到指定文件夹:

裁剪成功后,在主视图页显示裁剪图片:

当然,实际项目中最有可能的做法是:在本页上传、裁剪并保存。
□ 思路
→在上传图片视图页,把图片上传保存到一个临时文件夹Upload
→在编辑裁剪视图页,点击"裁剪"按钮,把JCrop能提供的参数,比如宽度、高度、离顶部距离,离底部距离,离左右端距离等封装成类,传递给控制器方法
→控制器方法根据接收到的参数,对图片裁剪,把图片保存到目标文件夹ProfileImages,并删除掉临时文件夹Upload里对应的图片。
为了配合上传图片的主视图页,需要一个与之对应的View Model,其中包含图片路径的属性。而这个图片路径属性不是简单的字段显示编辑,当主视图页的View Model被传递到图片编辑、裁剪视图页后,根据JScrop特点,肯定有针对图片的裁剪和预览区域,所以,我们需要针对主视图页View Model的路径属性使用UIHint特性,为该属性定制显示和编辑视图。主视图页的View Model为:
using System.ComponentModel.DataAnnotations; namespace MvcApplication1.Models
{
public class ProfileViewModel
{
[UIHint("ProfileImage")]
public string ImageUrl { get; set; }
}
}
在图片编辑、裁剪视图页,对应的View Model不仅有主视图页的View Model作为它的属性,还有与JCrop相关的属性,这些属性无需显示,只需要以隐藏域的方式存在着,通过JCrop的事件,把JCrop参数赋值给这些隐藏域。对应的View Model为:
using System.Web.Mvc; namespace MvcApplication1.Models
{
public class EditorInputModel
{
public ProfileViewModel Profile { get; set; }
[HiddenInput]
public double Top { get; set; }
[HiddenInput]
public double Bottom { get; set; }
[HiddenInput]
public double Left { get; set; }
[HiddenInput]
public double Right { get; set; }
[HiddenInput]
public double Width { get; set; }
[HiddenInput]
public double Height { get; set; }
}
}
在上传图片的主视图页中,需要引入Microsoft.Web.Helpers(通过NuGet),使用该命名空间下的FileUpload帮我们生成上传元素。
@using Microsoft.Web.Helpers
@model MvcApplication1.Models.ProfileViewModel @{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
} <h2>Index</h2>
@using (Html.BeginForm("Upload", "Home", FormMethod.Post, new {@encType = "multipart/form-data"}))
{
@Html.DisplayFor(x => x.ImageUrl)<br/>
@FileUpload.GetHtml(initialNumberOfFiles:1,includeFormTag:false, uploadText:"上传图片")<br/>
<input type="submit" name="submit" text="上传" />
}
在HomeController中:
action方法Upload用来接收来自主视图的View Model,把图片保存到临时文件夹Upload中,并把主视图的View Model赋值给编辑、裁剪视图中View Model的属性。
还需要引入System.Web.Helpers组件,该组件WebImage类,提供了针对上传图片处理的一些API。
action方Edit接收来自编辑、裁剪视图中View Model,根据参数,使用WebImage类的API对图片裁剪,保存到目标文件夹ProfileImages,并删除临时文件夹Upload中的相关图片。
using System.Web.Mvc;
using MvcApplication1.Models;
using System.Web.Helpers;
using System.IO; namespace MvcApplication1.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
} //如果图片上传成功就到裁剪页、即编辑页
[HttpPost]
public ActionResult Upload(ProfileViewModel model)
{
var image = WebImage.GetImageFromRequest(); //必须引用System.Web.Helpers程序集
if (image != null)
{
//限制图片的长度不能大于500像素
if (image.Width > 500)
{
image.Resize(500, ((500*image.Height)/image.Width));
} //根据图片的名称获取相对路径
var filename = Path.GetFileName(image.FileName);
//保存图片到指定文件夹
image.Save(Path.Combine("~/Upload/", filename)); //获取图片的绝对路径
filename = Path.Combine("../Upload/", filename);
model.ImageUrl = Url.Content(filename); var editModel = new EditorInputModel()
{
Profile = model,
Width = image.Width,
Height = image.Height,
Top = image.Height * 0.1,
Left = image.Width * 0.9,
Right = image.Width * 0.9,
Bottom = image.Height * 0.9
};
return View("Editor", editModel);
}
return View("Index", model);
} //裁剪页 编辑页
[HttpPost]
public ActionResult Edit(EditorInputModel editor)
{
//var image = new WebImage("~/" + editor.Profile.ImageUrl);
var image = new WebImage(editor.Profile.ImageUrl);
var height = image.Height;
var width = image.Width; image.Crop((int) editor.Top, (int) editor.Left, (int) (height - editor.Bottom), (int) (width - editor.Right));
var originalFile = editor.Profile.ImageUrl;//图片原路径 editor.Profile.ImageUrl = Url.Content("~/ProfileImages/" + Path.GetFileName(image.FileName));
image.Resize(100, 100, true, false);
image.Save(@"~" + editor.Profile.ImageUrl); System.IO.File.Delete(Server.MapPath(originalFile)); //把在Upload中的上传图片删除掉
return View("Index", editor.Profile);
} }
}
在编辑、裁剪视图页,需要引用Jcrop对应的css和js文件。
@model MvcApplication1.Models.EditorInputModel
@{
ViewBag.Title = "Editor";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Editor</h2>
<link href="~/Content/jquery.Jcrop.css" rel="stylesheet" />
<div id="mainform">
@using (Html.BeginForm("Edit", "Home", FormMethod.Post))
{
@Html.EditorFor(x => x.Profile.ImageUrl)
@Html.HiddenFor(x => x.Left)
@Html.HiddenFor(x => x.Right)
@Html.HiddenFor(x => x.Top)
@Html.HiddenFor(x => x.Bottom)
@Html.HiddenFor(x => x.Profile.ImageUrl)
<input type="submit" name="action" value="裁剪"/>
}
</div>
@section scripts
{
<script src="~/Scripts/jquery.Jcrop.js"></script>
<script type="text/javascript">
$(function() {
$('#profileImageEditor').Jcrop({
onChange: showPreview,
onSelect: showPreview,
setSelect: [@Model.Top, @Model.Left, @Model.Right, @Model.Bottom],
aspectRatio: 1
});
});
function showPreview(coords) {
if (parseInt(coords.w) > 0) {
$('#Top').val(coords.y);
$('#Left').val(coords.x);
$('#Bottom').val(coords.y2);
$('#Right').val(coords.x2);
var width = @Model.Width;
var height = @Model.Height;
var rx = 100 / coords.w;
var ry = 100 / coords.h;
$('#preview').css({
width: Math.round(rx * width) + 'px',
height: Math.round(ry * height) + 'px',
marginLeft: '-' + Math.round(rx * coords.x) + 'px',
marginTop: '-' + Math.round(ry * coords.y) + 'px'
});
}
}
</script>
}
既然为主视图View Model的ImageUrl打上了[UIHint("ProfileImage")]特性,这意味着必须有对应的自定义强类型视图。
public class ProfileViewModel
{
[UIHint("ProfileImage")]
public string ImageUrl { get; set; }
}
Views/Home/EditorTemplates/ProfileImage.cshtml,是针对ImageUrl属性的自定义编辑模版:
@model System.String
<div id="cropContainer">
<div id="cropPreview">
<img src="@(String.IsNullOrEmpty(Model) ? "" : Model)" id="preview" />
</div>
<div id="cropDisplay">
<img src="@(String.IsNullOrEmpty(Model) ? "" : Model)" id="profileImageEditor" />
</div>
</div>
Views/Home/DisplayTemplates/ProfileImage.cshtml,是针对ImageUrl属性的自定义显示模版:
@model System.String <img src="@(String.IsNullOrEmpty(Model) ? "" : Model)" id="profileImage" />
参考资料:
http://blog.tallan.com/2011/02/04/using-mvc3-razor-helpers-and-jcrop-to-upload-and-crop-images/
http://www.schnieds.com/2011/07/image-upload-crop-and-resize-with.html
http://zootfroot.blogspot.com/2010/12/mvc-file-upload-using-uploadify-with.html
MVC使用JCrop上传、裁剪图片的更多相关文章
- Django使用cropbox包来上传裁剪图片
1.使用cropbox包来上传裁剪图片,可见介绍:https://www.jianshu.com/p/6c269f0b48c0I ImgCrop包包括:css--style.css,js--cropb ...
- Spring4 MVC 多文件上传(图片并展示)
开始需要在pom.xml加入几个jar,分别是 <dependency> <groupId>commons-fileupload</groupId> <art ...
- MVC 中Simditor上传本地图片
1.引用样式和js文件 <link href="~/Content/scripts/plugins/simditor/css/simditor.css" rel=" ...
- ASP.NET MVC在服务端把异步上传的图片裁剪成不同尺寸分别保存,并设置上传目录的尺寸限制
我曾经试过使用JSAjaxFileUploader插件来把文件.照片以异步的方式上传,就像"MVC文件图片ajax上传轻量级解决方案,使用客户端JSAjaxFileUploader插件01- ...
- 基于Jcrop的图片上传裁剪加预览
最近自己没事的时候研究了下图片上传,发现之前写的是有bug的,这里自己重新写了一个! 1.页面结构 <!DOCTYPE html> <html lang="en" ...
- KindEditor上传本地图片在ASP.NET MVC的配置
http://www.cnblogs.com/upupto/archive/2010/08/24/1807202.html 本文解决KindEditor上传本地图片在ASP.NET MVC中的配置. ...
- MVC&WebForm对照学习:文件上传(以图片为例)
原文 http://www.tuicool.com/articles/myM7fe 主题 HTMLMVC模式Asp.net 博客园::首页:: :: :: ::管理 5 Posts :: 0 ...
- MVC应用程序显示上传的图片
MVC应用程序显示上传的图片 前两篇<MVC应用程序实现上传文件>http://www.cnblogs.com/insus/p/3590907.html和<MVC应用程序实现上传文件 ...
- 图片上传裁剪zyupload
图片上传控件用的是zyupload控件,使用过程中遇到了一些问题,特别记录下来 上图是目前的使用效果,这个控件我是用js代码动态添加出来的 HTML代码: <div class="wi ...
随机推荐
- 记一次对 Laravel-permission 项目的性能优化
我最近研究分析了在 SWIS上面创建的项目的性能.令人惊讶的是,最耗费性能的方法之一是优秀的 spatie/laravel-permission 包造成的. 经过查阅更多资料和研究,发现一个可能明显 ...
- who am i ?
Id:Ox9A82 Email:hucvbty@gmail.com 微博:http://weibo.com/1828621423 知乎:Ox9A82 常乐村男子职业技术学院 Syclover拖后腿成员 ...
- 21 包含min函数的栈
定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数. C++: class Solution { private: stack<int> dataStack ; stac ...
- winform框架源码-Devexpress开发框架
链接: https://pan.baidu.com/s/1TnDj6qftGEUl3sTB8QXs_w 提取码: 关注公众号[GitHubCN]回复获取 开发模式:C/S C/S采用的是dev14 ...
- Action(8):Error-26608:HTTP Status-Code=504(Gateway Time-out)
Action(8):Error-26608:HTTP Status-Code=504(Gateway Time-out) 若出现如下图问题, 1.在Vuser Generator中的Tools---& ...
- Educational Codeforces Round 45 (Rated for Div. 2) E - Post Lamps
E - Post Lamps 思路:一开始看错题,以为一个地方不能重复覆盖,我一想值这不是sb题吗,直接每个power check一下就好....复杂度nlogn 然后发现不是,这样的话,对于每个po ...
- 《Android源码设计模式》--策略模式
No1: 定义:策略模式定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换.策略模式让算法独立于使用它的客户而独立变化. No2: 使用场景: 1)针对同一类型问题的多种处理方式,仅 ...
- java中int和Integer比较
java中int和Integer比较 一,类型区别 我们知道java中由两种数据类型,即基本类型和对象类型,int就是基本数据类型,而Integer是一个class,也习惯把Integer叫做int的 ...
- python 文件内容修改替换操作
当我们读取文件中内容后,如果想要修改文件中的某一行或者某一个位置的内容,在python中是没有办法直接实现的,如果想要实现这样的操作只能先把文件所有的内容全部读取出来,然后进行匹配修改后写入到新的文件 ...
- 微信小程序 --01
微信小程序开发基础 -- 开发前的准备 缘由 1月9日张小龙微信小程序正式上线,因为微信,所以小程序从诞生开始就头戴巨大的光环,很多的团队,公司以及开发的个体都眼巴巴的盯着这个小程序.而那个时候我却在 ...