分享

在asp.net中使用jQuery实现类似QQ网站的图片切割效果

 昵称10504424 2013-12-06

今天要给大家介绍一个asp.net结合jQuery来切割图片的小程序,原理很简单,大致流程是:

加载原图 --> 用矩形框在原图上选取区域并将选取的顶点坐标和矩形尺寸发送至服务器 --> 由服务器切割原图并输出切割后的图片。下面我们就分别对这几个步骤详细展开讨论分析,并在最后附上小demo供大家参考。

1、在页面上加载原图

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

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

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

这个我们要用到一个jQuery插件Jcrop,感谢Jcrop,其项目页面地址:http:///content/Jcrop.html

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中如下调用来切割并输出:

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="" />

好了,整个过程就完成了,为了大家能更好的参考学习,下面附上小demo,点击下载

支持原创的同学果断要支持一下本文,欢迎大家转载本文。

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约