---
title: "有了jQuery.Jcrop，选取美女的哪个部位你说了算 "
author: "pleasetojava"
date: "2011-11-21T09:23:34Z"
tags: []
categories: ["编程语言"]
slug: "jquery-jcrop"
draft: false
lastmod: "2011-11-21T09:23:34Z"
id: 1270139
url: "https://pleasetojava.iteye.com/blog/1270139"
---

亲们，真的不愿意相信你们是被标题吸引进来的，但事实让我不得不承认男人的本性。但是，请放心，我绝非标题党（我最痛恨那些浪费大家时间的标题党了），既然你有幸进来了，那我得想办法让你带着收获离开。轻轻地我走了，正如我轻轻地来，我要带走楼主留给我的一片云彩……

好吧，收起我的放荡不羁，让我们立马切入正题，正如标题上说的，今天我们要在ASP.NET中用jQuery.Jcrop插件实现图片的选取功能，你想选取美女的哪个部位你说了算，我就管不着了。

总的来说，原理很简单，大致流程是：**在浏览器上加载原图 --&gt; 用矩形框在原图上选取区域并将选取的顶点坐标和矩形尺寸发送至服务器 --&gt; 服务器端用图片切割算法切割原图并输出切割后的图片**。下面我们就分别对这几个步骤详细展开讨论分析，并在最后附上小demo供大家参考。

**1、在页面上加载原图**

这个就不用多说了，就是在页面上显示一张图片，一个img标签搞定，不过为了下一步演示，还是贴一下代码

```
<img src="girl.jpg" kesrc="girl.jpg" alt="" id="TestImage" style="float: left;">
```

2、用矩形框在原图上选取区域

这个我们要用到一个jQuery插件Jcrop，感谢Jcrop，其项目页面地址：[http://deepliquid.com/content/Jcrop.html](http://deepliquid.com/content/Jcrop.html)，再次感谢。接下来就是运用这个插件来让我们能在原图上随意地切图。先在页面上放几个隐藏域，用来存放当前选取的顶点坐标及选取矩形的尺寸，再放一个保存按钮，点击保存按钮后将在服务器上保存切割后的图片。代码如下：

```
<form id="AvatarForm" action="">
<input id="x" name="x" type="hidden">
<input id="y" name="y" type="hidden">
<input id="w" name="w" type="hidden">
<input id="h" name="h" type="hidden">
<input class="input_btn" id="BtnSaveAvatar" value="确定保存" type="submit">
</form>
```

四个隐藏域分别表示x：左上顶点x坐标；y：左上顶点y坐标；w：选取矩形宽度；h：选取矩形长度。  
然后我们调用插件，做好初始化工作，引入js和css文件：

```
<script type="text/javascript" src="js/jquery.js" kesrc="js/jquery.js"></script>
<script type="text/javascript" src="js/Jcrop/js/jquery.Jcrop.js" kesrc="js/Jcrop/js/jquery.Jcrop.js"></script>
<link rel="stylesheet" href="js/Jcrop/css/jquery.Jcrop.css" kesrc="js/Jcrop/css/jquery.Jcrop.css" type="text/css">
```

初始化原图的js代码：

```
$(document).ready(function(){
    $('#TestImage').Jcrop({
        onChange: updateCoords,
        onSelect: updateCoords
    });
    $("#BtnSaveAvatar").click(function(){
        $.ajax({
            url:'Handler.ashx',
            data:{'x':$("#x").val(),'y':$("#y").val(),'w':$("#w").val(),'h':$("#h").val()},
            datatype : "text/json",
            type:'post',
            success: function(o){ window.location.href="result.aspx?url="+o;}    //成功后跳转到result页面查看切割后图片，把url
        });
return false; 
    });
});
function updateCoords(c){
    $('#x').val(c.x);
    $('#y').val(c.y);
    $('#w').val(c.w);
    $('#h').val(c.h);
};
```

经过上述步骤，我们很高兴的看到一位美女出现在我们眼前，并任由我们选取任何部位，很刺激吧，由于demo在最后，先在这截一张效果图吧

![](http://pic002.cnblogs.com/images/2011/117187/2011112100192592.jpg)

3、服务器端切割图片并输出切割后的图片：

切割图片的主要类代码如下：

```
public class ImageCut
{
///<summary>
/// 剪裁 -- 用GDI+
///</summary>
///<param name="b">原始Bitmap</param>
///<param name="StartX">开始坐标X</param>
///<param name="StartY">开始坐标Y</param>
///<param name="iWidth">宽度</param>
///<param name="iHeight">高度</param>
///<returns>剪裁后的Bitmap</returns>
    public Bitmap KiCut(Bitmap b)
    {
if (b == null)
        {
return null;
        }

int w = b.Width;
int h = b.Height;

if (X >= w || Y >= h)
        {
return null;
        }

if (X + Width > w)
        {
            Width = w - X;
        }

if (Y + Height > h)
        {
            Height = h - Y;
        }

try
        {
            Bitmap bmpOut = new Bitmap(Width, Height, PixelFormat.Format24bppRgb);

            Graphics g = Graphics.FromImage(bmpOut);
            g.DrawImage(b, new Rectangle(0, 0, Width, Height), new Rectangle(X, Y, Width, Height), GraphicsUnit.Pixel);
            g.Dispose();

return bmpOut;
        }
catch
        {
return null;
        }
    }

public int X = 0;
public int Y = 0;
public int Width = 120;
public int Height = 120;
public ImageCut(int x, int y, int width, int heigth)
    {
        X = x;
        Y = y;
        Width = width;
        Height = heigth;
    }
}
```

在Handler.ashx中，接收页面传递过来的切割图片的顶点坐标以及长宽尺寸，并调用C#图像切割类实现图片切割：

```
public void ProcessRequest (HttpContext context) {
string xstr = context.Request["x"];
string ystr = context.Request["y"];
string wstr = context.Request["w"];
string hstr = context.Request["h"];
string sourceFile = context.Server.MapPath("girl.jpg");
string savePath = "CutImage/" + Guid.NewGuid() + ".jpg";
int x = 0;
int y = 0;
int w = 1;
int h = 1;
try
        {
            x = int.Parse(xstr);
            y = int.Parse(ystr);
            w = int.Parse(wstr);
            h = int.Parse(hstr);
        }
catch { }

        ImageCut ic = new ImageCut(x, y, w, h);
        System.Drawing.Bitmap cuted = ic.KiCut(new System.Drawing.Bitmap(sourceFile));
string cutPath = context.Server.MapPath(savePath);
        cuted.Save(cutPath, System.Drawing.Imaging.ImageFormat.Jpeg);
        context.Response.Write(savePath);    //输出保存的路径，以便页面端接收路径显示切割后的图片
}
```

最后我们在Result.aspx页面上接收切割后的图片路径并显示切割后的图片：

```
<img src="<%=Request["url"] %>" alt="" />
```