上傳圖片前裁剪

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>圖像裁剪-Jcrop</title>
    <link rel="stylesheet" href="jquery.Jcrop.min.css" type="text/css" />
    <style>
        img {
            border: 0;
        }
        * {
            margin: 0;
            padding: 0;
        }
        .head {
            display: inline-block;
            width: auto;
            height: auto;
        }
        #target{
            max-width: 600px;
        }


        canvas {
            position: fixed;
            top: 400px;
            right: 0;
            border: 1px solid red;
            width: 340px;
            height: 208px;
        }
        #myCan{
            display: none;
        }
    </style>


</head>
<body>

<!-- 頭像 -->
<div class="head" >
    <img src=""  id="target" />
    <input type="file" id="file" onchange="changeFile()" style="display: none;"/>
</div>

<img src="" class="chang" alt="">
<button onClick="openBrowse()">上傳圖片</button>
<button onClick="uploadFile()">確認</button>
<!-- 畫板 -->
<canvas id="myCan" width="340" height="208"></canvas>
<script src="jquery.min.js"></script>
<script src="jquery.Jcrop.min.js"></script>
<script type="text/javascript">
    // 定義一些使用的變量
    var     jcrop_api,//jcrop對象
            boundx,//圖片實際顯示寬度
            boundy,//圖片實際顯示高度
            realWidth,// 真實圖片寬度
            realHeight, //真實圖片高度
             // 使用的jquery對象
            $target = $('#target'),
            xsize = 170,
            ysize = 104;

    //1、打開瀏覽器
    function openBrowse(){
        var ie=navigator.appName=="Microsoft Internet Explorer" ? true : false;
        if(ie){
            document.getElementById("file").click();
        }else{
            var a=document.createEvent("MouseEvents");
            a.initEvent("click", true, true);
            document.getElementById("file").dispatchEvent(a);
        }
    }

    //2、從 file 域獲取 本地圖片 url
    function getFileUrl(sourceId) {
        var url;
        if (navigator.userAgent.indexOf("MSIE")>=1) { // IE
            url = document.getElementById(sourceId).value;
        } else if(navigator.userAgent.indexOf("Firefox")>0) { // Firefox
            url = window.URL.createObjectURL(document.getElementById(sourceId).files.item(0));
        } else if(navigator.userAgent.indexOf("Chrome")>0) { // Chrome
            url = window.URL.createObjectURL(document.getElementById(sourceId).files.item(0));
        } else if(navigator.userAgent.indexOf("Safari")>0) { // Chrome
            url = window.URL.createObjectURL(document.getElementById(sourceId).files.item(0));
        }
        return url;
    }
    //選擇文件事件
    function changeFile() {
        var url = getFileUrl("file");//根據id獲取文件路徑
        preImg(url);
        return false;
    }
    //3、將本地圖片 顯示到瀏覽器上
    function preImg(url) {
        console.log('url===' + url);
        //圖片裁剪邏輯
        if(jcrop_api){//判斷jcrop_api是否被初始化過
            jcrop_api.destroy();
            console.log(jcrop_api);
        }
        //初始化圖片
        initTarget();
        var image = document.getElementById('target');
        image.onload=function(){//圖片加載是一個異步的過程
            //獲取圖片文件真實寬度和大小
            var img = new Image();
            img.onload=function(){
                realWidth = img.width;
                realHeight = img.height;
                //獲取圖片真實高度之後
                initJcrop();//初始化Jcrop插件
            };
            img.src = url;
        };
        image.src = url;
    }

    //初始化Jcrop插件
    function initJcrop(){
        $target.removeAttr("style");//清空上一次初始化設置的樣式
        $target.Jcrop({
            setSelect:[10,10,350,218],
            onChange: updatePreview,
            onSelect: updatePreview,
            aspectRatio: xsize / ysize
        },function(){
            //初始化後回調函數
            // 獲取圖片實際顯示的大小
            var bounds = this.getBounds();
            boundx = bounds[0];//圖片實際顯示寬度
            boundy = bounds[1];//圖片實際顯示高度
            // 保存jcrop_api變量
            updatePreview({
                h: 208,
                w: 340,
                x: 10,
                x2: 350,
                y: 10,
                y2: 218
            });
            jcrop_api = this;
            console.log(jcrop_api)
        });
    }

    //更新顯示預覽內容
    function updatePreview(c){
        console.log(c);
        if (parseInt(c.w) > 0) {
            //更新canvas畫板內容
            var img=document.getElementById("target");
            var ct=document.getElementById("myCan");
            var ctx=ct.getContext("2d");
            //清空畫板
            ctx.clearRect(0,0, ct.width, ct.height);
            //.drawImage(圖像對象,原圖像截取的起始X座標,原圖像截取的起始Y座標,原圖像截取的寬度,原圖像截取的高度,繪製圖像的起始X座標,繪製圖像的起始Y座標,繪製圖像所需要的寬度,繪製圖像所需要的高度);
            ctx.drawImage(img, c.x/boundx * realWidth,c.y/boundy * realHeight, c.w/boundx * realWidth, c.h/boundy * realHeight,0,0, 340, 208);
        }
    }

    //初始化預覽div內容
    function initTarget(){
        $target.removeAttr("style");//清空上一次初始化設置的樣式
        $target.css({
            maxWidth:  '100%',
            maxHeight: '100%'
        });
    }

    //文件上傳
    function uploadFile(){
        //獲取裁剪完後的base64圖片url,轉換爲blob
        var data=document.getElementById("myCan").toDataURL();
        var arr = data.split(',');
        var mime = arr[0].match(/:(.*?);/)[1];
        var bstr = atob(arr[1]);
        var n = bstr.length;
        var u8arr = new Uint8Array(n);
        while(n--){
            u8arr[n] = bstr.charCodeAt(n);
        }
        console.log(new File([u8arr],"壓縮", {type:mime}));
        $(".chang").attr("src",data)
    }

    //把base64位的toDataURL圖片轉換成blob
    function dataURLtoBlob(dataurl) {
        var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
                bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
        }
        return new Blob([u8arr], { type: mime });
    }

    window.onload = function () {
        //初始化圖片
        preImg('./1.jpg');
    };

</script>
</body>
</html>

文檔地址:http://code.ciaoca.com/jquery/jcrop/

demo下載地址:https://download.csdn.net/download/a707369808/10762306

文檔裏面有免費的下載地址

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章