五月综合缴情婷婷六月,色94色欧美sute亚洲线路二,日韩制服国产精品一区,色噜噜一区二区三区,香港三级午夜理伦三级三

您現(xiàn)在的位置: 365建站網(wǎng) > 365文章 > ASP.NET Ajax實(shí)現(xiàn)圖片剪裁

ASP.NET Ajax實(shí)現(xiàn)圖片剪裁

文章來源:365jz.com     點(diǎn)擊數(shù):657    更新時(shí)間:2009-09-14 10:43   參與評(píng)論
ASP.NET Ajax實(shí)現(xiàn)圖片剪裁
-

實(shí)現(xiàn)這個(gè)功能主要用到了JQuery和基于JQuery的圖片處理插件JCrop

JQuery可以下載下來,或者在代碼中這樣引用<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>。
JCrop
需要下載,其中還包括相應(yīng)的一些例子可以作為參考。

這個(gè)例子有三部分功能,一、圖片上傳,二、現(xiàn)實(shí)用戶上傳上來的圖片,三、圖片剪裁。
主要的流程是:用戶上傳圖片,顯示圖片,在用戶點(diǎn)擊剪裁按鈕之后,用ajax的方式顯示剪裁之后的圖片。
上傳圖片就用的ASP.NET自帶的文件上傳控件,整個(gè)文件上傳功能放在一個(gè)用戶空間里面。
每次用戶上傳了圖片以后,文件存放的位置持久化在一個(gè)xml文件中。
在用
JCrop實(shí)現(xiàn)剪裁功能的時(shí)候,需要在頁面中添加一些隱藏域來
存儲(chǔ)圖片剪裁中用到的坐標(biāo)和寬高等數(shù)據(jù)。剪裁則用JQueryAjax功能實(shí)現(xiàn)。


 1 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Pages_Default" %>
 2 
 3
 <%@ Register Src="../Controls/ImageUpload.ascx" TagName="ImageUpload" TagPrefix="uc1" %>
 4
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 5
 <html xmlns="http://www.w3.org/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
         // Remember to invoke within jQuery(window).load()
19
         // If you don't, Jcrop may not initialize properly
20
         jQuery(document).ready(function() {
21 
22
             jQuery('#cropbox').Jcrop({
23                 //onChange: showCoords,
24
                 onSelect: showCoords
25             });
26 
27
         });
28 
29
         function onCropClick() {
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("<img src='" + data.d + "' alt='' />");
42                 }
43             });
44         }
45 
46
         // Our simple event handler, called from onChange and onSelect
47
         // event handlers, as per the Jcrop invocation above
48
         function showCoords(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
         <!-- This is the image we're attaching Jcrop to -->
64
         <img runat="server" id="cropbox" />
65
         <input type="button" id="btnCrop" value=" Crop Image " 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" />


然后我們需要添加調(diào)用JCrop的代碼來實(shí)現(xiàn)圖片的剪裁

 1    <script type="text/javascript" language="Javascript">
 2
 3        jQuery(document).ready(function() {
 4
 5            jQuery('#cropbox').Jcrop({
 6                onSelect: showCoords
 7            }
);
 8        }
);
 9
10        function onCropClick() {
11
12            $.ajax({
13                type: "POST",
14                contentType: "application/json; charset=utf-8",
15                data: "{ pPartStartPointX: '" + $('#x').val() + "', pPartStartPointY: '" + $('#y').val() + "', pPartWidth: '" + $('#w').val() + "', pPartHeight: '" + $('#h').val() + "'}",
16                url: "Default.aspx/CroppedImage",
17                dataType: "json",
18                success: function(data) {
19                    $('#disp').html("<img src='" + data.d + "' alt='' />");
20                }

21            }
);
22        }

23
24        function showCoords(c) {
25            jQuery('#x').val(c.x);
26            jQuery('#y').val(c.y);
27            jQuery('#w').val(c.w);
28            jQuery('#h').val(c.h);
29        }
;
30
31    
</script>

這個(gè)代碼都很簡(jiǎn)單。JCrop處理id為cropbox的img中的圖片。在onSelect事件中添加函數(shù)showCoords來記錄用戶選中圖片區(qū)域的數(shù)據(jù)。
并在剪裁按鈕的點(diǎn)擊事件中實(shí)現(xiàn)Ajax的功能,將后臺(tái)處理好的圖片顯示在頁面上。

所需的命名空間
1using System;
2using System.Web;
3using System.Web.Services;

為什么要用System.Web.Services這個(gè)命名空間呢,因?yàn)槲覀冇肑Query調(diào)用后臺(tái)代碼時(shí)用的是后臺(tái)的頁面方法
 1    [WebMethod]
 2    public static string CroppedImage(int pPartStartPointX, int pPartStartPointY, int pPartWidth, int pPartHeight)
 3    {
 4        XmlHelper xmlHelper = new XmlHelper();
 5        xmlHelper.XmlPath = HttpContext.Current.Server.MapPath("~/App_Data/ImagePaths.xml");
 6        string originalPath = xmlHelper.GetImagepath();
 7        string savePath = HttpContext.Current.Server.MapPath("~/Images/CropImg/");
 8        string filename = ImageHelper.CropImage(originalPath, savePath, pPartWidth, pPartHeight, pPartStartPointX, pPartStartPointY);
 9
10        string fullpath = "../Images/CropImg/" + filename;
11        return fullpath;
12    }

前面提到過用戶控件,上傳圖片并記錄圖片的存放路徑。存放圖片路徑主要通過類XmlHelper來實(shí)現(xiàn)。
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="ImageUpload.ascx.cs" Inherits="Controls_ImageUpload" %>
<%--<asp:PlaceHolder ID="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=" Up Load " 
                onclick
="btnUpload_Click" />
        
</td>
    
</tr>
</table>

后臺(tái)代碼
 1using System;
 2using System.Web.UI.HtmlControls;
 3
 4public partial class Controls_ImageUpload : System.Web.UI.UserControl
 5{
 6    private readonly string IMG_PATH = "~/Images/Upload/";
 7    private XmlHelper _xmlHelper = new XmlHelper();
 8
 9    /// <summary>
10    /// Name of a control to operate
11    /// </summary>

12    public string ControlName getset; }
13
14    protected void Page_Load(object sender, EventArgs e)
15    {
16        if (!IsPostBack)
17        {
18            SetPathInfo();
19        }

20    }

21
22    protected void btnUpload_Click(object sender, EventArgs e)
23    {
24        try
25        {
26            // Specify the path on the server to
27            // save the uploaded file to.
28            String savePath = Server.MapPath(IMG_PATH);
29
30            // Before attempting to perform operations
31            // on the file, verify that the FileUpload 
32            // control contains a file.
33            if (imgUpload.HasFile)
34            {
35                // Get the name of the file to upload.
36                String fileName = imgUpload.FileName;
37
38                // Append the name of the file to upload to the path.
39                savePath += fileName;
40
41                // Call the SaveAs method to save the 
42                // uploaded file to the specified path.
43                // This example does not perform all
44                // the necessary error checking.               
45                // If a file with the same name
46                // already exists in the specified path,  
47                // the uploaded file overwrites it.
48                imgUpload.SaveAs(savePath);
49
50                _xmlHelper.XmlPath = Server.MapPath("~/App_Data/ImagePaths.xml");
51                _xmlHelper.StoreImagePath(savePath);
52
53                SetPathInfo();
54            }

55        }

56        catch (Exception)
57        {
58            this.Page.ClientScript.RegisterStartupScript(this.GetType(), """alert('Image can not be uploaded, please check!'"true);
59        }

60    }

61
62
63    private void SetPathInfo()
64    {
65        string serverPath = "~/Images/Upload/";
66
67        XmlHelper xmlHelper = new XmlHelper();
68        xmlHelper.XmlPath = Server.MapPath("~/App_Data/ImagePaths.xml");
69        string imgPath = xmlHelper.GetImagepath();
70        string filename = GetFileName(imgPath);
71
72        serverPath += filename;
73
74        HtmlImage cropbox = (HtmlImage)Parent.FindControl("cropbox");
75        if (cropbox != null)
76            cropbox.Src = serverPath;
77        HtmlImage preview = (HtmlImage)Parent.FindControl("preview");
78        if (preview != null)
79            preview.Src = serverPath;
80
81        Context.Items["imgsrc"= serverPath;
82    }

83
84    private string GetFileName(string fullname)
85    {
86        // Validation of string is not implemented temperarily
87        int index = fullname.LastIndexOf("\\");
88        string filename = fullname.Substring(index + 1);
89
90        return filename;
91    }

92}

93

XmlHelper類中用到的主要方法
 1public void StoreImagePath(string img)
 2    {
 3        try
 4        {
 5            if (_xdoc == null)
 6            {
 7                _xdoc = XDocument.Load(XmlPath);
 8            }

 9
10            _xdoc.Root.Descendants().Remove();
11            _xdoc.Root.Add(new XElement("path", img));
12            _xdoc.Save(this.XmlPath);
13        }

14        catch
15        {
16            throw new Exception("Error occured in adding image path.");
17        }

18    }

19
20    public string GetImagepath()
21    {
22        string imagePath = string.Empty;
23
24        try
25        {
26            if (_xdoc == null)
27            {
28                _xdoc = XDocument.Load(XmlPath);
29            }

30
31            imagePath = _xdoc.Root.Descendants().First().Value.ToString();
32        }

33        catch
34        {
35            throw new Exception("Error occured in getting image path.");
36        }

37
38        return imagePath;
39    }

之后就是一個(gè)很重要的方法了。剪裁圖片的方法,放在ImageHelper類中。
 1public static string CropImage(string originamImgPath, string imgPath, int width, int height, int x, int y)
 2    {
 3        string filename = DateTime.Now.ToString("yyyyMMddHHmmss"+ ".jpg";
 4        byte[] CropImage = Crop(originamImgPath, width, height, x, y);
 5        using (MemoryStream ms = new MemoryStream(CropImage, 0, CropImage.Length))
 6        {
 7            ms.Write(CropImage, 0, CropImage.Length);
 8            using (System.Drawing.Image CroppedImage = System.Drawing.Image.FromStream(ms, true))
 9            {
10                string SaveTo = imgPath + filename;
11                CroppedImage.Save(SaveTo, CroppedImage.RawFormat);
12            }

13        }

14
15        return filename;
16    }

17
18    private static byte[] Crop(string Img, int Width, int Height, int X, int Y)
19    {
20        try
21        {
22            using (Image OriginalImage = Image.FromFile(Img))
23            {
24                using (Bitmap bmp = new Bitmap(Width, Height, OriginalImage.PixelFormat))
25                {
26                    bmp.SetResolution(OriginalImage.HorizontalResolution, OriginalImage.VerticalResolution);
27                    using (Graphics Graphic = Graphics.FromImage(bmp))
28                    {
29                        Graphic.SmoothingMode = SmoothingMode.AntiAlias;
30                        Graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
31                        Graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
32                        Graphic.DrawImage(OriginalImage, new Rectangle(00, Width, Height), X, Y, Width, Height, GraphicsUnit.Pixel);
33                        MemoryStream ms = new MemoryStream();
34                        bmp.Save(ms, OriginalImage.RawFormat);
35                        return ms.GetBuffer();
36                    }

37                }

38            }

39        }

40        catch (Exception Ex)
41        {
42            throw (Ex);
43        }

44    }

看下效果,demo階段先不做優(yōu)化了。
開始


顯示上傳的圖片


圖片剪裁




就寫到這里了,希望這篇對(duì)大家有幫助!
Tag標(biāo)簽: ASP.NET,AJAX,jquery,image cropping,cropping,ajax image cropping,圖片剪裁,剪裁

如對(duì)本文有疑問,請(qǐng)?zhí)峤坏浇涣髡搲?,廣大熱心網(wǎng)友會(huì)為你解答?。?點(diǎn)擊進(jìn)入論壇

發(fā)表評(píng)論 (657人查看,0條評(píng)論)
請(qǐng)自覺遵守互聯(lián)網(wǎng)相關(guān)的政策法規(guī),嚴(yán)禁發(fā)布色情、暴力、反動(dòng)的言論。
昵稱:
最新評(píng)論
------分隔線----------------------------

其它欄目

· 建站教程
· 365學(xué)習(xí)

業(yè)務(wù)咨詢

· 技術(shù)支持
· 服務(wù)時(shí)間:9:00-18:00
365建站網(wǎng)二維碼

Powered by 365建站網(wǎng) RSS地圖 HTML地圖

copyright © 2013-2024 版權(quán)所有 鄂ICP備17013400號(hào)