Jcrop簡單實用


今天有一個項目的功能需求 “在上傳照片的時候能進行裁剪”,網上找了下,發現有Jcrop這款插件,自己試了下,感覺很不錯,蠻好用的。又能增加用戶體驗,測試了兼容性也很好,所以在這里分享下

 首先,可以到官網上下載這款插件 htttp://www.jquery.com ,下載后有需要的話可以看下里面的demo

在項目中,只要在head中引用

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

前台頁面,要加上4個隱藏域,分別記錄剪切后的x,y坐標和長,寬。附上代碼

    <div>
    <!--需要剪切的圖片-->
        <img src="gq_nav.jpg" alt="" id="TestImage" style="float: left;">
    </div>
    <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>
    <!--簡介后顯示的圖片-->
    <img id="CutImage" />

接着實例化Jcrop

 

   <script>
        $(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 (imgUrl) {
                        $("#CutImage").attr("src", imgUrl);
                    }
                });
                return false;
            });
        });
        function updateCoords(c) {
            $('#x').val(c.x);
            $('#y').val(c.y);
            $('#w').val(c.w);
            $('#h').val(c.h);
        };
    </script>

 

之后看下運行效果圖

好了,效果出來了,然后要保存截取后的圖片了,這樣在剛剛的腳本中可以看到用ajax提交到Handler.ashx上去處理,附上代碼

 

public void ProcessRequest(HttpContext context)
    {
        
        //接收位置x,y。
        //接收長寬w,h。
        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("gq_nav.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);    //輸出保存的路徑,以便頁面端接收路徑顯示切割后的圖片
    }

Handler.ashx中可以看到生成新的圖片是交給ImageCut這個類去做的,這里也附上代碼

 

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;
    }
}

 

這樣就可以實現在線剪裁圖片的效果了。因為覺得這款插件還算不錯,所以特此分享下,希望大師們不要取笑,如果哪位有更好的建議或其他類似的插件,也希望
能分享給小弟。

另:附上這個插件的屬性

allowSelect true 允許新選框
allowMove true 允許選框移動
allowResize true 允許選框縮放
trackDocument true  
baseClass “jcrop” 基礎樣式名前綴。說明:class=”jcrop-holder”,更改的只是其中的 jcrop。
addClass null 添加樣式。例:假設值為 “test”,那么會添加樣式到
bgColor “black” 背景顏色。顏色關鍵字、HEX、RGB 均可。
bgOpacity 0.6 背景透明度
bgFade false 使用背景過渡效果
borderOpacity 0.4 選框邊框透明度
handleOpacity 0.5 縮放按鈕透明度
handleSize 9 縮放按鈕大小
handleOffset 5 縮放按鈕與邊框的距離
aspectRatio 0 選框寬高比。說明:width/height
keySupport true 支持鍵盤控制。按鍵列表:上下左右(移動)、Esc(取消)、Tab(跳出裁剪框,到下一個)
cornerHandles true 允許邊角縮放
sideHandles true 允許四邊縮放
drawBorders true 繪制邊框
dragEdges true 允許拖動邊框
fixedSupport true  
touchSupport null  
boxWidth 0 畫布寬度
boxHeight 0 畫布高度
boundary 2 邊界。說明:可以從邊界開始拖動鼠標選擇裁剪區域
fadeTime 400 過度效果的時間
animationDelay 20 動畫延遲
swingSpeed 3 過渡速度
minSelect [0,0] 選框最小選擇尺寸。說明:若選框小於該尺寸,則自動取消選擇
maxSize [0,0] 選框最大尺寸
minSize [0,0] 選框最小尺寸
onChange function(){} 選框改變時的事件
onSelect function(){} 選框選定時的事件
onRelease function(){} 取消選框時的事件

 

API 接口

 

名稱 說明
setImage(string) 設定(或改變)圖像。例:jcrop_api.setImage(“newpic.jpg”)
setOptions(object) 設定(或改變)參數,格式與初始化設置參數一樣
setSelect(array) 創建選框,參數格式為:[x,y,x2,y2]
animateTo(array) 用動畫效果創建選框,參數格式為:[x,y,x2,y2]
release() 取消選框
disable() 禁用 Jcrop。說明:已有選框不會被清除。
enable() 啟用 Jcrop
destroy() 移除 Jcrop
tellSelect() 獲取選框的值(實際尺寸)。例子:console.log(jcrop_api.tellSelect())
tellScaled() 獲取選框的值(界面尺寸)。例子:console.log(jcrop_api.tellScaled())
getBounds() 獲取圖片實際尺寸,格式為:[w,h]
getWidgetSize() 獲取圖片顯示尺寸,格式為:[w,h]
getScaleFactor() 獲取圖片縮放的比例,格式為:[w,h]

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM