cropper實現基本的裁剪圖片並上傳


使用cropper之前需要先引用 cropper.css 和 cropper.js

cropper 官網:https://fengyuanchen.github.io/cropper/

cropper.css下載:https://github.com/fengyuanchen/cropperjs/tree/master/docs/css

cropper.js下載:https://github.com/fengyuanchen/cropperjs/tree/master/docs/js

 

然后我們來了解一下cropper的基本屬性及方法

參數options

   1. viewMode(定義cropper的視圖模式)

   類型:number;默認:0;可以使用0,1,2,3;

   0:沒有限制,3可以移動到2外。
   1 : 3只能在2內移動。
   2:2圖片 不全部鋪滿1 (即縮小時可以有一邊出現空隙)
   3:2圖片填充整個1

   2. dragMode (定義cropper的拖拽模式)

  類型: String
  默認: ‘crop’
  選項:
  ‘crop’: 可以產生一個新的裁剪框3
  ‘move’: 只可以移動3
  ‘none’: 什么也不處理

   3. aspectRatio—-裁剪框的寬高比

  類型:number;默認:NAN;
  在默認的時候。可以隨意改變裁剪框的大小;我這里的設置的值為 16/9;

   4. data—如果您已經存儲了以前的數據,那么在構建時將會自動將其傳遞給setData方法。(具體怎么用還不知道)

   5. preview—-添加額外的元素(容器)以供預覽

  類型:Element / String 默認:“ ”;
  注意這里是一個dom元素。必須可以被Document.querySelectorAll獲取到;
  preview:".small",
  HTML結構:<div class="small"></div>;注意一定要設置small的寬高;最好和裁剪比例一致;還有如果要想正確的顯示出裁剪的區域需要加上樣式overflow: hidden;

  6. center—裁剪框在圖片正中心。

 

  7. background–顯示容器的網格背景。(就是后面的馬賽克)

 

  8. rotatable–是否允許旋轉圖像。

  9. scalable–是否允許縮放圖像。

  10. zoomable–是否允許放大圖像。

  11. ready—插件准備完成執行的函數(只執行一次)。

  12. crop—剪裁框發生變化執行的函數。

  13. zoom—剪裁框縮放的時候執行的函數。

 

Methods 方法

使用方法示例:
$().cropper({ ready: function () { $().cropper('method', argument1, , argument2, ..., argumentN); } });

1. crop 手動顯示裁剪框
  
$("#image").cropper({
    autoCrop: false, //關閉自動顯示裁剪框
    ready: function () {
      $(this).cropper('crop');
    }
  });

2 . reset—-將圖像和裁剪框重置為初始狀態
  $("#reset").on("click", function () { $('#image').cropper('reset'); })
3 . clear—清除裁切框
  $("#clear").on("click", function () { $('#image').cropper('clear'); })
4. replace(url[, onlyColorChanged])—替換圖像的src並重新構建cropper
  $("#replace").on("click", function () {
    $('#image').cropper('replace',"./images/111.jpeg",true );
  })
5. enable()—解鎖,鎖定的裁切框(與disable相對應)
  
$("#enable").on("click", function () {
    $('#image').cropper('enable');
  })

6 . disable()—鎖定的裁切框(裁切框不可移動)(與enable相對應)
  $("#disable").on("click", function () { $('#image').cropper('disable'); })
7.destroy()—銷毀cropper並從圖像中刪除整個cropper。
  $("#destroy").on("click", function () {
    $('#image').cropper('destroy');
  })


代碼示例:
 
  <style> 
    .row{
      margin-bottom: 5px;
    }
    #photo {
      max-width: 100%;
    }
    .img-preview {
      width: 100px;
      height: 100px;
      overflow: hidden;
    }
    button {
      margin-top:10px;
    }
    #result {
      width: 150px;
      height: 150px;
    }
  </style>

  <div class="row"> <div class="col-sm-12 text-center"> <label for="input" class="btn btn-danger" id=""> <span>選擇圖片</span> <input type="file" id="input" class="sr-only"> </label> </div> </div> <div class="row"> <div class="col-sm-6 col-sm-offset-2"> <img src="" id="photo"> </div> <div class="col-sm-2"> <div> <p> 預覽(100*100): </p> <div class="img-preview"> </div> </div> <button class="btn btn-primary" onclick="crop()">裁剪圖片</button> <div> <br/> <p> 結果: </p> <img src="" alt="裁剪結果" id="result"> </div> </div> </div>
  <script> // 修改自官方demo的js var initCropper = function (img, input){ var $image = img; var options = { aspectRatio: 1, // 縱橫比 viewMode: 2, preview: '.img-preview' // 預覽圖的class名 }; $image.cropper(options); var $inputImage = input; var uploadedImageURL; if (URL) { // 給input添加監聽 $inputImage.change(function () { var files = this.files; var file; if (!$image.data('cropper')) { return; } if (files && files.length) { file = files[0]; // 判斷是否是圖像文件 if (/^image\/\w+$/.test(file.type)) { // 如果URL已存在就先釋放 if (uploadedImageURL) { URL.revokeObjectURL(uploadedImageURL); } uploadedImageURL = URL.createObjectURL(file); // 銷毀cropper后更改src屬性再重新創建cropper $image.cropper('destroy').attr('src', uploadedImageURL).cropper(options); $inputImage.val(''); } else { window.alert('請選擇一個圖像文件!'); } } }); } else { $inputImage.prop('disabled', true).addClass('disabled'); } } var crop = function () {
            var photo = $('#photo').cropper('getCroppedCanvas', {
                 // 裁剪后的長寬
                height: 160
            }).toDataURL('image/png');
            console.log(photo);
            $.ajax({
                url: '/Attachment/Uploadphoto', // 要上傳的地址
                method: 'post',
                data: { dataURL:photo },
                success: function (data) {
                    $('#result').attr('src', data).show();
                    $('#img').val(data);
                },
                error: function (data) {
                    alert(data);
                }
            });
        }
$(function(){ initCropper($('#photo'),$('#input')); }); </script>
后台代碼:
   /// <summary>
        /// 上傳裁剪圖片(頭像)
        /// </summary>
        /// <param name="dataURL"></param>
        /// <returns></returns>
        public ActionResult Uploadphoto(string dataURL)
        {
            //將‘,’以前的多余字符串去除
            string base64 = dataURL.Substring(dataURL.IndexOf(",") + 1);
            byte[] bytearr = Convert.FromBase64String(base64);
            MemoryStream ms = new MemoryStream(bytearr);
            //將MemoryStream對象轉換成Bitmap對象
            Bitmap bmp = new Bitmap(ms);
            //關閉流
            ms.Close();
            string dir = DateTime.Now.ToString("yyyyMMdd");
            string abpath = Server.MapPath($"/upload/{dir}/");
            if (!Directory.Exists(abpath))
            {
                Directory.CreateDirectory(abpath);
            }
            string newname = Guid.NewGuid().ToString().Substring(0, 6) + ".png";

            bmp.Save(abpath + newname, System.Drawing.Imaging.ImageFormat.Png);

            return Content($"/upload/{dir}/{newname}");
        }


免責聲明!

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



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