实现这个功能主要用到了JQuery和基于JQuery的图片处理插件JCrop。
JQuery可以下载下来,或者在代码中这样引用<scripttype="text/javascript" src="/ajax/libs/jquery/1.3/jquery.min.js"></script>。
JCrop需要下载,其中还包括相应的一些例子可以作为参考。
这个例子有三部分功能,一、图片上传,二、现实用户上传上来的图片,三、图片剪裁。
主要的流程是:用户上传图片,显示图片,在用户点击剪裁按钮之后,用ajax的方式显示剪裁之后的图片。
上传图片就用的自带的文件上传控件,整个文件上传功能放在一个用户空间里面。
每次用户上传了图片以后,文件存放的位置持久化在一个xml文件中。
在用JCrop实现剪裁功能的时候,需要在页面中添加一些隐藏域来
存储图片剪裁中用到的坐标和宽高等数据。剪裁则用JQuery的Ajax功能实现。
1 <% @PageLanguage = " C# " AutoEventWireup = " true " CodeFile = " Default.aspx.cs " Inherits = " Pages_Default " %>
2
3 <% @RegisterSrc = " ../Controls/ImageUpload.ascx " TagName = " ImageUpload " TagPrefix = " uc1 " %>
4 <! DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""/TR/xhtml1/DTD/xhtml1-transitional.dtd">
5 < html xmlns ="/1999/xhtml" >
6 < head runat ="server" >
7 < title ></ title >
8
9 < script src ="../Scripts/jquery.min.js" type ="text/javascript" ></ script >
10
11 < script src ="../Scripts/jquery.Jcrop.js" type ="text/javascript" ></ script >
12
13 < link href ="../Style/jquery.Jcrop.css" rel ="stylesheet" type ="text/css" />
14 < link href ="../Style/demos.css" rel ="stylesheet" type ="text/css" />
15
16 < script type ="text/javascript" language ="Javascript" >
17
18 // RemembertoinvokewithinjQuery(window).load()
19 // Ifyoudon't,Jcropmaynotinitializeproperly
20 jQuery(document).ready( function(){
21
22 jQuery( ' #cropbox ').Jcrop({
23 // onChange:showCoords,
24 onSelect:showCoords
25 });
26
27 });
28
29 functiononCropClick(){
30
31 // alert("{pPartStartPointX:'"+$('#x').val()+"',pPartStartPointY:'"+$('#y').val()+"',pPartWidth:'"+$('#w').val()+"',pPartHeight:'"+$('#h').val()+"'}");
32 $.ajax({
33 type: " POST ",
34 contentType: " application/json;charset=utf-8 ",
35 data: " {pPartStartPointX:' " + $( ' #x ' ).val() + " ',pPartStartPointY:' " + $( ' #y ' ).val() + " ',pPartWidth:' " + $( ' #w ' ).val() + " ',pPartHeight:' " + $( ' #h ' ).val() + " '} ",
36 url: " Default.aspx/CroppedImage ",
37 dataType: " json ",
38 success: function(data){
39 // alert(data.d);
40 // $("#CustomerDetails").html(data);
41 $( ' #disp ' ).html( " <imgsrc=' " + data.d + " 'alt=''/> ");
42 }
43 });
44 }
45
46 // Oursimpleeventhandler,calledfromonChangeandonSelect
47 // eventhandlers,aspertheJcropinvocationabove
48 functionshowCoords(c){
49 jQuery( ' #x ').val(c.x);
50 jQuery( ' #y ').val(c.y);
51 // jQuery('#x2').val(c.x2);
52 // jQuery('#y2').val(c.y2);
53 jQuery( ' #w ').val(c.w);
54 jQuery( ' #h ').val(c.h);
55 };
56
57 </ script >
58
59 </ head >
60 < body >
61 < form id ="form1" runat ="server" >
62 < div >
63 <!-- Thisistheimagewe'reattachingJcropto -->
64 < img runat ="server" id ="cropbox" />
65 < input type ="button" id ="btnCrop" value ="CropImage" onclick ="onCropClick();" />
66 < div id ="disp" >
67 </ div >
68 < label >
69 <% -- X1 -- %>
70 < input type ="hidden" size ="4" id ="x" name ="x" /></ label >
71 < label >
72 <% -- Y1 -- %>
73 < input type ="hidden" size ="4" id ="y" name ="y" /></ label >
74 < label >
75 <% -- X2 -- %>
76 < input type ="hidden" size ="4" id ="x2" name ="x2" /></ label >
77 < label >
78 <% -- Y2 -- %>
79 < input type ="hidden" size ="4" id ="y2" name ="y2" /></ label >
80 < label >
81 <% -- W -- %>
82 < input type ="hidden" size ="4" id ="w" name ="w" /></ label >
83 < label >
84 <% -- H -- %>
85 < input type ="hidden" size ="4" id ="h" name ="h" /></ label >
86 < uc1:ImageUpload ID ="ImageUpload1" runat ="server" />
87 </ div >
88 </ form >
89 </ body >
90 </ html >
注意在页面代码中添加需要的javascript和css样式表
1 < script src ="../Scripts/jquery.min.js" type ="text/javascript" ></ script >
2 < script src ="../Scripts/jquery.Jcrop.js" type ="text/javascript" ></ script >
3 < link href ="../Style/jquery.Jcrop.css" rel ="stylesheet" type ="text/css" />
4 < link href ="../Style/demos.css" rel ="stylesheet" type ="text/css" />
然后我们需要添加调用JCrop的代码来实现图片的剪裁
1 < script type ="text/javascript" language ="Javascript" >
2
3jQuery(document).ready(function(){
4
5jQuery('#cropbox').Jcrop({
6onSelect:showCoords
7});
8});
9
10functiononCropClick(){
11
12$.ajax({
13type:"POST",
14contentType:"application/json;charset=utf-8",
15data:"{pPartStartPointX:'"+$('#x').val()+"',pPartStartPointY:'"+$('#y').val()+"',pPartWidth:'"+$('#w').val()+"',pPartHeight:'"+$('#h').val()+"'}",
16url:"Default.aspx/CroppedImage",
17dataType:"json",
18success:function(data){
19$('#disp').html("<imgsrc='"+data.d+"'alt=''/>");
20}
21});
22}
23
24functionshowCoords(c){
25jQuery('#x').val(c.x);
26jQuery('#y').val(c.y);
27jQuery('#w').val(c.w);
28jQuery('#h').val(c.h);
29};
30
31 </ script >
这个代码都很简单。JCrop处理id为cropbox的img中的图片。在onSelect事件中添加函数showCoords来记录用户选中图片区域的数据。
并在剪裁按钮的点击事件中实现Ajax的功能,将后台处理好的图片显示在页面上。
所需的命名空间
1 using System;
2 using System.Web;
3 using System.Web.Services;
为什么要用System.Web.Services这个命名空间呢,因为我们用JQuery调用后台代码时用的是后台的页面方法
1 [WebMethod]
2 public static string CroppedImage( int pPartStartPointX, int pPartStartPointY, int pPartWidth, int pPartHeight)
3 {
4XmlHelperxmlHelper=newXmlHelper();
5xmlHelper.XmlPath=HttpContext.Current.Server.MapPath("~/App_Data/ImagePaths.xml");
6stringoriginalPath=xmlHelper.GetImagepath();
7stringsavePath=HttpContext.Current.Server.MapPath("~/Images/CropImg/");
8stringfilename=ImageHelper.CropImage(originalPath,savePath,pPartWidth,pPartHeight,pPartStartPointX,pPartStartPointY);
9
10stringfullpath="../Images/CropImg/"+filename;
11returnfullpath;
12}
前面提到过用户控件,上传图片并记录图片的存放路径。存放图片路径主要通过类XmlHelper来实现。
<% @ControlLanguage = " C# " AutoEventWireup = " true " CodeFile = " ImageUpload.ascx.cs " Inherits = " Controls_ImageUpload " %>
<% --< asp:PlaceHolderID = " imageContainer " runat = " server " ></ asp:PlaceHolder >-- %>
< table >
< tr >
< td >
< asp:FileUpload ID ="imgUpload" runat ="server" />
</ td >
</ tr >
< tr >
< td >
< asp:Button ID ="btnUpload" runat ="server" Text ="UpLoad"
onclick ="btnUpload_Click" />
</ td >
</ tr >
</ table >
后台代码
1 using System;
2 using System.Web.UI.HtmlControls;
3
4 public partial class Controls_ImageUpload:System.Web.UI.UserControl
5 {
6privatereadonlystringIMG_PATH="~/Images/Upload/";
7privateXmlHelper_xmlHelper=newXmlHelper();
8
9///<summary>
10///Nameofacontroltooperate
11///</summary>
12publicstringControlName{get;set;}
13
14protectedvoidPage_Load(objectsender,EventArgse)
15{
16if(!IsPostBack)
17{
18SetPathInfo();
19}
20}
21
22protectedvoidbtnUpload_Click(objectsender,EventArgse)
23{
24try
25{
26//Specifythepathontheserverto
27//savetheuploadedfileto.
28StringsavePath=Server.MapPath(IMG_PATH);
29
30//Beforeattemptingtoperformoperations
31//onthefile,verifythattheFileUpload
32//controlcontainsafile.
33if(imgUpload.HasFile)
34{
35//Getthenameofthefiletoupload.
36StringfileName=imgUpload.FileName;
37
38//Appendthenameofthefiletouploadtothepath.
39savePath+=fileName;
40
41//CalltheSaveAsmethodtosavethe
42//uploadedfiletothespecifiedpath.
43//Thisexampledoesnotperformall
44//thenecessaryerrorchecking.
45//Ifafilewiththesamename
46//alreadyexistsinthespecifiedpath,
47//theuploadedfileoverwritesit.
48imgUpload.SaveAs(savePath);
49
50_xmlHelper.XmlPath=Server.MapPath("~/App_Data/ImagePaths.xml");
51_xmlHelper.StoreImagePath(savePath);
52
53SetPathInfo();
54}
55}
56catch(Exception)
57{
58this.Page.ClientScript.RegisterStartupScript(this.GetType(),"","alert('Imagecannotbeuploaded,pleasecheck!'",true);
59}
60}
61
62
63privatevoidSetPathInfo()
64{
65stringserverPath="~/Images/Upload/";
66
67XmlHelperxmlHelper=newXmlHelper();
68xmlHelper.XmlPath=Server.MapPath("~/App_Data/ImagePaths.xml");
69stringimgPath=xmlHelper.GetImagepath();
70stringfilename=GetFileName(imgPath);
71
72serverPath+=filename;
73
74HtmlImagecropbox=(HtmlImage)Parent.FindControl("cropbox");
75if(cropbox!=null)
76cropbox.Src=serverPath;
77HtmlImagepreview=(HtmlImage)Parent.FindControl("preview");
78if(preview!=null)
79preview.Src=serverPath;
80
81Context.Items["imgsrc"]=serverPath;
82}
83
84privatestringGetFileName(stringfullname)
85{
86//Validationofstringisnotimplementedtemperarily
87intindex=fullname.LastIndexOf("\\");
88stringfilename=fullname.Substring(index+1);
89
90returnfilename;
91}
92}
93
XmlHelper类中用到的主要方法
1 public void StoreImagePath( string img)
2 {
3try
4{
5if(_xdoc==null)
6{
7_xdoc=XDocument.Load(XmlPath);
8}
9
10_xdoc.Root.Descendants().Remove();
11_xdoc.Root.Add(newXElement("path",img));
12_xdoc.Save(this.XmlPath);
13}
14catch
15{
16thrownewException("Erroroccuredinaddingimagepath.");
17}
18}
19
20 public string GetImagepath()
21 {
22stringimagePath=string.Empty;
23
24try
25{
26if(_xdoc==null)
27{
28_xdoc=XDocument.Load(XmlPath);
29}
30
31imagePath=_xdoc.Root.Descendants().First().Value.ToString();
32}
33catch
34{
35thrownewException("Erroroccuredingettingimagepath.");
36}
37
38returnimagePath;
39}
之后就是一个很重要的方法了。剪裁图片的方法,放在ImageHelper类中。
1 public static string CropImage( string originamImgPath, string imgPath, int width, int height, int x, int y)
2 {
3stringfilename=DateTime.Now.ToString("yyyyMMddHHmmss")+".jpg";
4byte[]CropImage=Crop(originamImgPath,width,height,x,y);
5using(MemoryStreamms=newMemoryStream(CropImage,0,CropImage.Length))
6{
7ms.Write(CropImage,0,CropImage.Length);
8using(System.Drawing.ImageCroppedImage=System.Drawing.Image.FromStream(ms,true))
9{
10stringSaveTo=imgPath+filename;
11CroppedImage.Save(SaveTo,CroppedImage.RawFormat);
12}
13}
14
15returnfilename;
16}
17
18 private static byte []Crop( string Img, int Width, int Height, int X, int Y)
19 {
20try
21{
22using(ImageOriginalImage=Image.FromFile(Img))
23{
24using(Bitmapbmp=newBitmap(Width,Height,OriginalImage.PixelFormat))
25{
26bmp.SetResolution(OriginalImage.HorizontalResolution,OriginalImage.VerticalResolution);
27using(GraphicsGraphic=Graphics.FromImage(bmp))
28{
29Graphic.SmoothingMode=SmoothingMode.AntiAlias;
30Graphic.InterpolationMode=InterpolationMode.HighQualityBicubic;
31Graphic.PixelOffsetMode=PixelOffsetMode.HighQuality;
32Graphic.DrawImage(OriginalImage,newRectangle(0,0,Width,Height),X,Y,Width,Height,GraphicsUnit.Pixel);
33MemoryStreamms=newMemoryStream();
34bmp.Save(ms,OriginalImage.RawFormat);
35returnms.GetBuffer();
36}
37}
38}
39}
40catch(ExceptionEx)
41{
42throw(Ex);
43}
44}
看下效果,demo阶段先不做优化了。
开始
显示上传的图片
图片剪裁
就写到这里了,希望这篇对大家有帮助! 欢迎加群互相学习,共同进步。QQ群:iOS: 58099570 | Android: 572064792 | Nodejs:329118122 做人要厚道,转载请注明出处!
本文转自张昺华-sky博客园博客,原文链接:/sunshine-anycall/archive//08/25/1553273.html ,如需转载请自行联系原作者