工作需要参考网上的一些代码做了个图片截取工具,最后干脆封装成一个jquery的插件。

除了jquery,本插件还引用了UI库,包括ui.draggable.js

ImageCropper 演示

ImageCropper 下载

插件用法:

1 var imageCropper = $('#imgBackground').imageCropper();

要注意的是此插件只应用在有src属性的img标签上。

通过插件输出的参数,即可以通过服务器端代码截取图片,比如:

1 $('#imgCroppedImage').attr('src', 'CropImage.ashx?p=' + imageCropper.settings.imagePath + '&z=' + imageCropper.settings.zoomLevel + '&t=' + imageCropper.settings.top + '&l=' + imageCropper.settings.left + '&w=' + imageCropper.settings.width + '&h=' + imageCropper.settings.height + '&' + Math.random());

asp.net hander CropImage.ashx:

代码

 1 public class CropImage : IHttpHandler
 2 {
 3     public void ProcessRequest(HttpContext context)
 4     {
 5         string imgPath = Convert.ToString(context.Request["p"]);
 6         float zoomLevel = Convert.ToSingle(context.Request["z"]);
 7         int top = Convert.ToInt32(context.Request["t"]);
 8         int left = Convert.ToInt32(context.Request["l"]);
 9         int width = Convert.ToInt32(context.Request["w"]);
10         int height = Convert.ToInt32(context.Request["h"]);
11         context.Response.ContentType = "image/jpeg";
12         Crop(HttpContext.Current.Server.MapPath(imgPath), zoomLevel, top, left, width, height).WriteTo(context.Response.OutputStream);
13     }
14 
15     public MemoryStream Crop(string imgPath, float zoomLevel, int top, int left, int width, int height)
16     {
17         Image img = Image.FromFile(imgPath);
18         Bitmap bitmap = new Bitmap(width, height);
19         Graphics g = Graphics.FromImage(bitmap);
20         g.DrawImage(img, new Rectangle(0, 0, width, height), new Rectangle((int)(left / zoomLevel), (int)(top / zoomLevel), (int)(width / zoomLevel), (int)(height / zoomLevel)), GraphicsUnit.Pixel);
21         MemoryStream ms = new MemoryStream();
22         bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
23         img.Dispose();
24         g.Dispose();
25         bitmap.Dispose();
26         return ms;
27     }
28 
29     public bool IsReusable
30     {
31         get
32         {
33             return false;
34         }
35     }
36 }

重点是插件,因为源代码注释比较全,直接贴代码在这:

  1 /**
  2 * Copyright (c) 2010 Viewercq (http://www.cnblogs.com/viewercq/archive/2010/04/04/1704093.html)
  3 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
  4 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
  5 *
  6 * Version: 1.0
  7 *
  8 * Demo: https://dl.dropbox.com/u/4390741/ImageCropper.htm
  9 */
 10 ; (function($) {
 11     $.fn.extend({
 12         imageCropper: function(options) {
 13             if (!this.is('img') || typeof this.attr('src') == 'undefined' || this.attr('src') == '') {
 14                 throw 'Please notice that this jquery plguin only could be applied to img and the src of img could not be null!';
 15             }
 16             var defaults = {
 17                 //原图路径
 18                 imagePath: this.attr('src'),
 19                 //缩放级别
 20                 zoomLevel: 1,
 21                 //图片相对于截取框是否居中
 22                 center: false,
 23                 //截取框与图片的相对位置
 24                 left: 0, top: 0,
 25                 //截取框的大小
 26                 width: 200, height: 200,
 27                 //工作区大小
 28                 cropWorkAreaSize: { width: 600, height: 400 },
 29                 //截取框相对于工作区的位置
 30                 cropFrameRect: { center: true, top: 0, left: 0 },
 31                 //缩放范围
 32                 zoom: { min: 0, max: 2, step: 0.01 },
 33                 //回调函数
 34                 callbacks: {
 35                     //移动图片后
 36                     dragging: false,
 37                     //缩放后
 38                     zoomed: false
 39                 }
 40             };
 41             if (options) {
 42                 defaults = $.extend(defaults, options);
 43             }
 44             return new imageCropper(this, defaults);
 45         }
 46     });
 47 
 48     function imageCropper(image, settings) {
 49         this.init(image, settings);
 50     };
 51 
 52     imageCropper.prototype = {
 53         settings: false,
 54         wrapper: $('<div class="image-cropper-wrapper"/>'),
 55         zoomWrapper: $('<div class="zoom-wrapper"><div class="zoom-out-button"/><div class="zoom-scrollbar"><div class="zoom-scroller"/></div><div class="zoom-in-button"/></div>'),
 56         img: false,
 57         init: function(image, settings) {
 58             var context = this;
 59             this.settings = settings;
 60             image.addClass('background-img');
 61             //生成html
 62             image.wrap(this.wrapper).wrap('<div class="crop-work-area"/>').wrap('<div class="crop-background"/>');
 63             this.wrapper = $('.image-cropper-wrapper');
 64             $('.crop-work-area', this.wrapper).append('<div class="crop-frame"><img class="foreground-img" src="" /></div><div class="drag-containment"/>');
 65             this.wrapper.append(this.zoomWrapper);
 66 
 67             $('.image-cropper-wrapper', this.wrapper).disableSelection();
 68             this.reset();
 69 
 70             //图片的拖动
 71             $('.crop-background', this.wrapper).draggable({
 72                 containment: $('.drag-containment', this.wrapper),
 73                 cursor: 'move',
 74                 drag: function(event, ui) {
 75                     var self = $(this).data('draggable');
 76                     //同时移动前景图
 77                     $('.foreground-img', this.wrapper).css({
 78                         left: (parseInt(self.position.left) - context.settings.cropFrameRect.left - 1) + 'px',
 79                         top: (parseInt(self.position.top) - context.settings.cropFrameRect.top - 1) + 'px'
 80                     });
 81                     //得到截图左上点坐标
 82                     context.settings.left = context.settings.cropFrameRect.left - parseInt($(this).css('left'));
 83                     context.settings.top = context.settings.cropFrameRect.top - parseInt($(this).css('top'));
 84                     //移动图片的callback
 85                     context.fireCallback(context.settings.callbacks.dragging);
 86                 }
 87             });
 88             $('.foreground-img', this.wrapper).draggable({
 89                 containment: $('.drag-containment', this.wrapper),
 90                 cursor: 'move',
 91                 drag: function(event, ui) {
 92                     var self = $(this).data('draggable');
 93                     //同时移动背景
 94                     $('.crop-background', this.wrapper).css({
 95                         left: (parseInt(self.position.left) + context.settings.cropFrameRect.left + 1) + 'px',
 96                         top: (parseInt(self.position.top) + context.settings.cropFrameRect.top + 1) + 'px'
 97                     });
 98                     //得到截图左上点坐标
 99                     context.settings.left = context.settings.cropFrameRect.left - parseInt($('.crop-background', this.wrapper).css('left'));
100                     context.settings.top = context.settings.cropFrameRect.top - parseInt($('.crop-background', this.wrapper).css('top'));
101                     //移动图片的callback
102                     context.fireCallback(context.settings.callbacks.dragging);
103                 }
104             });
105             //点击缩放
106             $('.zoom-out-button,.zoom-in-button', this.wrapper).click(function() {
107                 var step = $(this).hasClass('zoom-in-button') ? context.settings.zoom.step : -context.settings.zoom.step;
108                 var tempZoomLevel = context.formatNumber(context.settings.zoomLevel + step, 3);
109                 //如果缩放级别超出范围 或者 缩放导致图片右下角没在截取框内 则取消缩放
110                 if (context.settings.zoomLevel >= context.settings.zoom.min
111                     && context.settings.zoomLevel <= context.settings.zoom.max
112                     && parseInt($('.crop-background', this.wrapper).css('left')) + tempZoomLevel * context.img.width > context.settings.cropFrameRect.left + context.settings.width
113                     && parseInt($('.crop-background', this.wrapper).css('top')) + tempZoomLevel * context.img.height > context.settings.cropFrameRect.top + context.settings.height
114                 ) {
115                     context.settings.zoomLevel = tempZoomLevel;
116                     context.zoom(context.img.width * context.settings.zoomLevel, context.img.height * context.settings.zoomLevel);
117                     $('.zoom-scroller', this.wrapper).css('left', context.settings.zoomLevel * 200 / (context.settings.zoom.max - context.settings.zoom.min) + 'px');
118                 }
119                 context.fireCallback(context.settings.callbacks.zoomed);
120             });
121             //滚动条缩放
122             var cancelZoomScroll = false;
123             $('.zoom-scroller', this.wrapper).draggable({
124                 containment: $('.zoom-scrollbar', this.wrapper),
125                 axis: 'x',
126                 drag: function(event, ui) {
127                     var tempZoomLevel = (context.settings.zoom.max - context.settings.zoom.min) * parseInt($(this).css('left')) / 200;
128                     //如果缩放级别超出范围 或者 缩放导致图片右下角没在截取框内 则取消缩放
129                     if (parseInt($('.crop-background', this.wrapper).css('left')) + tempZoomLevel * context.img.width > context.settings.cropFrameRect.left + context.settings.width
130                         && parseInt($('.crop-background', this.wrapper).css('top')) + tempZoomLevel * context.img.height > context.settings.cropFrameRect.top + context.settings.height
131                     ) {
132                         context.settings.zoomLevel = tempZoomLevel;
133                         context.zoom(context.img.width * context.settings.zoomLevel, context.img.height * context.settings.zoomLevel);
134                         cancelZoomScroll = false;
135                         context.fireCallback(context.settings.callbacks.zoomed);
136                     }
137                     else {
138                         cancelZoomScroll = true;
139                     }
140                 },
141                 stop: function(event, ui) {
142                     //如果缩放级别无效 则重置滚动条的值
143                     if (cancelZoomScroll) {
144                         $('.zoom-scroller', this.wrapper).css('left', context.settings.zoomLevel * 200 / (context.settings.zoom.max - context.settings.zoom.min) + 'px');
145                     }
146                 }
147             });
148         },
149         reset: function() {
150             this.img = new Image();
151             this.img.src = this.settings.imagePath;
152             //截取框大于工作区,则放大工作区
153             var tempSize = {
154                 width: Math.max(this.settings.cropWorkAreaSize.width, this.settings.width),
155                 height: Math.max(this.settings.cropWorkAreaSize.height, this.settings.height)
156             };
157             //如果截取框在工作区中居中,则重新设置截取框的位置
158             if (this.settings.cropFrameRect.center) {
159                 this.settings.cropFrameRect.left = (tempSize.width - this.settings.width) / 2;
160                 this.settings.cropFrameRect.top = (tempSize.height - this.settings.height) / 2;
161             }
162             //如果截取框在图片中居中,则重新设置图片与截取框的相对位置
163             if (this.settings.center) {
164                 this.settings.left = (this.img.width * this.settings.zoomLevel - this.settings.width) / 2;
165                 this.settings.top = (this.img.height * this.settings.zoomLevel - this.settings.height) / 2;
166             }
167 
168             this.wrapper.width(tempSize.width + 2).height(tempSize.height + 25);
169             $('.foreground-img,.background-img', this.wrapper).attr('src', this.settings.imagePath);
170             $('.crop-work-area', this.wrapper).width(tempSize.width).height(tempSize.height);
171             $('.crop-frame', this.wrapper).css({
172                 left: this.settings.cropFrameRect.left + 'px',
173                 top: this.settings.cropFrameRect.top + 'px',
174                 width: this.settings.width + 'px',
175                 height: this.settings.height + 'px'
176             });
177             $('.foreground-img', this.wrapper).css({
178                 left: (-this.settings.cropFrameRect.left - 1) + 'px',
179                 top: (-this.settings.cropFrameRect.top - 1) + 'px'
180             });
181             $('.zoom-scroller', this.wrapper).css('left', this.settings.zoomLevel * 200 / (this.settings.zoom.max - this.settings.zoom.min) + 'px');
182 
183 
184             $('.crop-background', this.wrapper).css({
185                 opacity: 0.3,
186                 left: this.settings.cropFrameRect.left - this.settings.left + 'px',
187                 top: this.settings.cropFrameRect.top - this.settings.top + 'px'
188             });
189             $('.foreground-img', this.wrapper).css({
190                 left: -this.settings.left + 'px',
191                 top: -this.settings.top + 'px'
192             });
193 
194             this.settings.left = this.settings.cropFrameRect.left - parseInt($('.crop-background', this.wrapper).css('left'));
195             this.settings.top = this.settings.cropFrameRect.top - parseInt($('.crop-background', this.wrapper).css('top'));
196 
197             this.zoom(this.img.width * this.settings.zoomLevel, this.img.height * this.settings.zoomLevel);
198         },
199         zoom: function(width, height) {
200             $('.crop-background, .background-img, .foreground-img', this.wrapper).width(width).height(height);
201             //调整拖动限制框
202             $('.drag-containment', this.wrapper).css({
203                 left: this.settings.cropFrameRect.left + this.settings.width - this.settings.zoomLevel * this.img.width + 1 + 'px',
204                 top: this.settings.cropFrameRect.top + this.settings.height - this.settings.zoomLevel * this.img.height + 1 + 'px',
205                 width: 2 * this.settings.zoomLevel * this.img.width - this.settings.width + 'px',
206                 height: 2 * this.settings.zoomLevel * this.img.height - this.settings.height + 'px'
207             });
208         },
209         formatNumber: function(number, bit) {
210             return Math.round(number * Math.pow(10, bit)) / Math.pow(10, bit);
211         },
212         fireCallback: function(fn) {
213             if ($.isFunction(fn)) {
214                 fn.call(this);
215             };
216         }
217     };
218 })(jQuery);
219 

参考:http://www.cnblogs.com/brightwang/archive/2008/09/10/1288148.html

转载于:https://www.cnblogs.com/viewercq/archive/2010/04/07/1704093.html

jquery插件:图片截取工具jquery.imagecropper.js相关推荐

  1. jquery实现截取pc图片_jquery 图片截取工具jquery.imagecropper.js

    除了jquery,本插件还引用了UI库,包括ui.draggable.js ImageCropper 演示需要asp.net支持.测试通过 ImageCropper 下载 https://www.jb ...

  2. jquery插件图片浏览

    jquery插件图片浏览 jquery代码部分 (function($){$.fn.mPicsList = function(options){var picsImgs = $(this).find( ...

  3. jQuery插件之Cooki(jquery.cookie.js)

    一.jQuery.Cookie.js插件是一个轻量级的Cookie管理插件. 特别提醒,今日发现一个特别的错误,google浏览器提示:has no method $.cookie.火狐浏览器提示:$ ...

  4. jquery 背景图片_使用jQuery的美丽背景图片导航

    jquery 背景图片 View demo 查看演示 Download Source 下载源 In this tutorial we are going to create a beautiful n ...

  5. jQuery 插件取url参数[jquery.url.js]的使用以及文件下载

    方法一. 如题,直接上调用代码: jQuery.url.param("c") "c"就是当前url中的参数,记得要引用jquery.js和jquery.url. ...

  6. 前端学习(1033):jquery插件-图片懒加载

    1下载插件 2html css和js引入 ctrl+h 快速替换 必须最后插入

  7. JAVA绘制图片原理_java开发_图片截取工具实现原理

    先来看看效果: 测试一: 原图: 效果图: 测试二: 原图: 效果图: 代码部分: /** * */ package com.b510; import java.awt.rectangle; impo ...

  8. 51 jQuery插件库

    技术交流QQ群:1027579432,欢迎你的加入! 欢迎关注我的微信公众号:CurryCoder的程序人生 1.jQuery插件 jQuery功能比较有限,想要更复杂的特效功能,可以借助于jQuer ...

  9. 让人期待的2011年度最佳 jQuery 插件发布啦

    近日,国外著名博客WDL发布了2011年度最佳 jQuery 插件.jQuery 自2006年发布以来,经过五年的迅速发展,目前已是最流行和使用最广泛的 JavaScript 框架.jQuery 的易 ...

最新文章

  1. 1155 Heap Paths (30 分)【难度: 一般 / 知识点: 堆 堆的遍历】
  2. http简介看这篇就够了
  3. 算法练习day19——190410(数组中重复的数字、替换空格、从尾到头打印链表)
  4. Find the AFei Numbers
  5. LeetCode 83. 删除排序链表中的重复元素(链表)
  6. Linux连接状态为syn_recv,linux 服务器 syn*** 大量SYN_RECV状态处理
  7. sql跟踪 oracle,oracle SQL语句跟踪详解
  8. 个性艺术创意风采人物海报,psd分层模板
  9. linux默认网关地址,linux shell 获取默认网关地址
  10. 21天jenkins打卡前置准备:linux环境
  11. 目标跟踪数据集GOT-10k的配置
  12. App Inventor 2连接模拟器一直失败的问题解决
  13. WinIo驱动级键盘模拟编程
  14. 滴滴收购优步谈判过程_如何为未来安排优步
  15. ffmpeg每隔1秒抽取视频的1帧画面
  16. 数据共享-spark中共享变量深度解析
  17. 快递webservice接口
  18. 可视化实验一:大数据可视化工具—Excel
  19. 如何配置管理员权限并删除文件
  20. 考研到底有多累?有人心累,有人很快乐

热门文章

  1. linux video属性_Linux 下Video 的制作方法
  2. Windows下运行Redis-网盘链接-简单粗暴-亲测有用
  3. leedcode刷题——整数反转
  4. OpenCV:无法启动此程序,因为计算机中丢失opencv_world310.dll
  5. Page Cache引起的业务问题处理
  6. Anaconda 国内镜像源整理
  7. Qt自定义委托在QTableView中绘制控件、图片、文字
  8. (四)Paint函数实现QTableView中增加QCheckBox的方法
  9. [每日一题] 11gOCP 1z0-052 :2013-09-24 temporary tables.........................................C11...
  10. 物化视图的刷新方式说明