jQuery之Jcrop
头像裁剪是一个经常用到的功能,实现原理也较为简单,就是在本地选择好所需裁剪图片的坐标,将坐标发送到服务器,由服务器执行图片裁剪操作。
jQuery插件Jcrop提供了强大的图片裁剪坐标选择插件。一下来介绍它的用法。本处采用了AJAX本地上传一张图片的方法让用户裁剪。很多验证没有做,因为作为一个关于Jcrop的例子,很多验证不如与本文研究的范畴。服务器端采用MVC3实现。
直接贴代码,详解注释里面有了。
一、前台页面代码。
![](/assets/blank.gif)
<link href="http://www.cnblogs.com/Content/jquery.Jcrop.css" rel="stylesheet" type="text/css" /> <script src="http://www.cnblogs.com/Content/jquery-1.7.1.js" type="text/javascript"></script> <script src="http://www.cnblogs.com/Content/ajaxfileupload.js" type="text/javascript"></script> <script src="http://www.cnblogs.com/Content/jquery.Jcrop.js" type="text/javascript"></script><script type="text/javascript">$(function () {$(":button").click(function () {//当点击上传按钮时,AJAX上传图片到服务器ajaxFileUpload();})})//当裁剪框变动时,将左上角相对图片的X坐标与Y坐标,宽度以及高度放到<input type="hidden">中(上传到服务器上裁剪会用到)function showCoords(c) {$("#p1").text(c.x + " " + c.y + " " + c.w + " " + c.h );$("#x1").val(c.x);$("#y1").val(c.y);$("#cw").val(c.w);$("#ch").val(c.h);}//当AJAX上传图片操作function ajaxFileUpload() {$.ajaxFileUpload({url: '/uploadandcut/upload?action=up', //用于文件上传的服务器端请求地址up参数标记此次是上传操作还是裁剪操作secureuri: false, //一般设置为false,是否安全上传fileElementId: 'file1', //文件上传控件的id属性 <input type="file" id="file" name="file" />dataType: 'json', //返回值类型 一般设置为json 期望服务器传回的数据类型success: function (data, status) //服务器成功响应处理函数{//上传成功后在将服务器上刚刚上传的图片显示在img1上$("#img1").attr("src", data.imgurl);if (typeof (data.error) != 'undefined') {if (data.error != '') {alert(data.error);} else {alert(data.msg);}}//同时启动裁剪操作,触发裁剪框显示,让用户选择图片区域$("#img1").Jcrop({bgColor: 'black',bgOpacity: .4,setSelect: [100, 100, 150,150], //设定4个角的初始位置aspectRatio: 1 / 1,onChange: showCoords, //当裁剪框变动时执行的函数onSelect: showCoords, //当选择完成时执行的函数});},error: function (data, status, e)//服务器响应失败处理函数{alert(e);}})return false;}</script><div><p><input type="file" id="file1" name="file" /></p><input type="button" value="上传" /><p><img id="img1" alt="上传成功啦!" src="" /></p><p id="p1"></p><form id="FaceUpload" name="FaceUpload" method="post" enctype="multipart/form-data" action="/uploadandcut/Upload?action=cut"><input type="hidden" id="x1" name="x1" value="0" /><input type="hidden" id="y1" name="y1" value="0" /><input type="hidden" id="cw" name="cw" value="0" /><input type="hidden" id="ch" name="ch" value="0" /><input type="submit" value="裁剪上传" /></form></div>
![](/assets/blank.gif)
二、后台代码
![](/assets/blank.gif)
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Drawing;namespace UploadAndCut.Controllers {public class UploadAndCutController : Controller{/// <summary>/// 打开页面/// </summary>/// <returns></returns>public ActionResult Index(){return View();}/// <summary>/// 上传操作,包括提交表单与AJAX上传图片/// </summary>/// <returns></returns>public ActionResult Upload(){string action = HttpContext.Request.QueryString["action"];//判断用户的操作类型switch (action.ToLower()){#region 当为上传图片操作时case "up":foreach (string upload in Request.Files){if (!Request.Files[upload].HasFile()){continue;}string ExtensionName = Path.GetExtension(Request.Files[upload].FileName).ToLower();if (ExtensionName != ".jpg" && ExtensionName != ".png" && ExtensionName != ".gif" && ExtensionName != ".bmp"){return Redirect("/Tips/tip?error=您上传的图片不符合格式!");}string ImgPath = Server.MapPath("/uploads/" + "img" + ExtensionName);Request.Files[upload].SaveAs(ImgPath);}string error = "";string msg = "上传成功";string imgurl = "/uploads/img.jpg";string res = "{ error:'" + error + "', msg:'" + msg + "',imgurl:'" + imgurl + "'}";return Content(res);break;#endregion#region 当为裁剪图片操作时case "cut":string strx1 = HttpContext.Request.Form["x1"];string stry1 = HttpContext.Request.Form["y1"];string strcw = HttpContext.Request.Form["cw"];string strch = HttpContext.Request.Form["ch"];int intx1 = Convert.ToInt32(strx1);int inty1 = Convert.ToInt32(stry1);int intcw = Convert.ToInt32(strcw);int intch = Convert.ToInt32(strch);Stream imgStream = GetLocalStream(Server.MapPath("/uploads/" + "img.jpg"));//System.Drawing.Image initImage = System.Drawing.Image.FromStream(imgStream);Cut(imgStream, Server.MapPath("/uploads/img.jpg"), intx1, inty1, intcw, intch, 100);return Redirect("/uploadandcut/index");break;#endregiondefault:return null;break;}}/// <summary>/// 将一个文件读成字符流/// </summary>/// <param name="InFilePath"></param>/// <returns></returns>public static Stream GetLocalStream(string InFilePath){return new MemoryStream(ReadFileReturnBytes(InFilePath));}/// <summary>从文件中读取二进制数据</summary>/// <param name="filePath">文件路径</param>/// <returns> byte[]二进制数据</returns>public static byte[] ReadFileReturnBytes(string filePath){FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);BinaryReader br = new BinaryReader(fs);byte[] buff = br.ReadBytes((int)fs.Length);br.Close();fs.Close();return buff;}#region 裁剪操作public static void Cut(System.IO.Stream fromFile, string fileSaveUrl, int xPosition, int yPosition, int width, int height, int quality){//创建目录//原始图片(获取原始图片创建对象,并使用流中嵌入的颜色管理信息)System.Drawing.Image initImage = System.Drawing.Image.FromStream(fromFile, true);//原始图片的宽、高int initWidth = initImage.Width;int initHeight = initImage.Height;if (xPosition + width > initWidth)width = initWidth - xPosition;if (yPosition + height > initHeight)height = initHeight - yPosition;//与原图相等直接保存if ((width >= initWidth && height >= initHeight) || (width < 1 && height < 1)){initImage.Save(fileSaveUrl, System.Drawing.Imaging.ImageFormat.Jpeg);}else{System.Drawing.Image pickedImage = null;System.Drawing.Graphics pickedG = null;//对象实例化pickedImage = new System.Drawing.Bitmap(width, height);pickedG = System.Drawing.Graphics.FromImage(pickedImage);//设置质量pickedG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;pickedG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;//定位System.Drawing.Rectangle fromR = new System.Drawing.Rectangle(xPosition, yPosition, width, height);System.Drawing.Rectangle toR = new System.Drawing.Rectangle(0, 0, width, height);//画图pickedG.DrawImage(initImage, toR, fromR, System.Drawing.GraphicsUnit.Pixel);//关键质量控制//获取系统编码类型数组,包含了jpeg,bmp,png,gif,tiffSystem.Drawing.Imaging.ImageCodecInfo[] icis = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders();System.Drawing.Imaging.ImageCodecInfo ici = null;foreach (System.Drawing.Imaging.ImageCodecInfo i in icis){if (i.MimeType == "image/jpeg" || i.MimeType == "image/bmp" || i.MimeType == "image/png" || i.MimeType == "image/gif"){ici = i;}}System.Drawing.Imaging.EncoderParameters ep = new System.Drawing.Imaging.EncoderParameters(1);ep.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)quality);//保存缩略图pickedImage.Save(fileSaveUrl, ici, ep);//释放关键质量控制所用资源ep.Dispose();//释放截图资源pickedG.Dispose();pickedImage.Dispose();//释放原始图片资源initImage.Dispose();}}#endregion} }
![](/assets/blank.gif)
还有一个扩展方法,在DEMO里面会有,不粘贴了。DEMO下载地址
转载于:https://www.cnblogs.com/mingxuantongxue/p/3909905.html
jQuery之Jcrop相关推荐
- php ci 处理图片 裁剪,jquery.form + Jcrop + CI框架实现图片裁剪上传
功能: 1.通过jquery.form上传图片,并按一定比例显示预览图. 2.通过Jcrop裁剪图片,并显示裁剪预览图 3.通过CI的图像处理类保存剪切后图片 问题: 1.通过jquery.form来 ...
- jquery插件jcrop的初步认识与用法
最近在写项目的过程中,需要用到图像裁切上传,所以接触了插件jcrop.这个插件的裁切功能主要是获取裁切图片后的x坐标,y坐标与裁切图片的宽度和高度.该插件运行后,dom格式如下 关于该插件的源码,以及 ...
- (转)有了jQuery.Jcrop,选取美女的哪个部位你说了算
原文地址:http://www.cnblogs.com/sxwgf/archive/2011/11/21/2256645.html 哈哈,亲们,真的不愿意相信你们是被标题吸引进来的,但事实让我不得不承 ...
- 在asp.net中使用jQuery实现类似QQ网站的图片切割效果
今天要给大家介绍一个asp.net结合jQuery来切割图片的小程序,原理很简单,大致流程是: 加载原图 --> 用矩形框在原图上选取区域并将选取的顶点坐标和矩形尺寸发送至服务器 --> ...
- php jcrop,PHP结合JQueryJcrop实现图片裁切实例详解
我们经常可以看到一些网站上有图片剪切的功能,或许你会觉得这一功能炫目华丽,神秘莫测!但是今天介绍的一款专用于图片裁切的插件jquery.Jcrop.min.js就将揭开图片剪切的神秘面纱.使用这个插件 ...
- 前端:jQuery笔记
前端:jQuery笔记 此系列文章乃是学习jQuery的学习笔记. Asp.net MVC Comet推送 摘要: 一.简介 在Asp.net MVC实现的Comet推送的原理很简单. 服务器端:接收 ...
- 使用jcrop实现裁切图片
jcrop为基于jquery库实现的图片裁切插件.当使用该插件使需要引入jquery和jcrop(包括js文件和css文件). //css文件的引入<link rel="stylesh ...
- Jcrop是一个功能强大的图像裁剪引擎
Jcrop是一个功能强大的图像裁剪引擎jQuery的. 它的设计使开发人员可以很容易地直接集成了先进的图像裁剪功能集成到任何基于Web的应用程序在不牺牲动力和灵活性(或编码,测试和调试的星期).Jcr ...
- jcrop java_SpringMVC结合Jcrop实现图片裁剪
本文实例为大家分享了SpringMVC结合Jcrop实现图片裁剪的具体代码,供大家参考,具体内容如下 一.jsp页面: method="post" enctype="mu ...
最新文章
- deepsort原理快速弄懂——时效比最高的
- jQuery进行简单验证的正则表达式
- SQL Server 中WITH (NOLOCK)浅析
- python库整理:networkx 包
- 以太网实习_物联网通信硬件入门项目—光纤收发器(1)——实习内容,适用范围,技术及收益...
- JZOJ 1016. 【PKU3321】苹果树
- Java 调用接口工具类并设置请求和传输超时时间
- python读取字典元素笔记_python学习笔记:字典的使用示例详解
- 距离向量算法_阿里北大:深度哈希算法最新综述
- LeetCode之Max Points on a Line Total
- mysqldump导出数据库视图_mysql中如何用mysqldump批量如何导出视图view啊?
- c++ namespace_c++语法2、c执行命名空间输入输出
- 数据从mysql迁移至oracle时知识点记录(一)
- html配色插件,【插件技巧】设计师必备配色max插件
- css ul1,CSS 列表样式 ul
- 舆情传染病时空分析文献阅读笔记
- Moving to Linux: Kiss the Blue Screen of Death Goodbye!读书笔记1
- 用免费新浪云sea搭建个人云服务器
- 深入了解JVM之内存模型(四)
- Linux -- Ubuntu下载deepin wine依赖问题笔记