找回密码
 立即注册
首页 业界区 业界 Cropper.js 裁剪图片,并利用 FormData 对象将裁剪图片 ...

Cropper.js 裁剪图片,并利用 FormData 对象将裁剪图片生成 Blob 数据上传到服务器

士沌 2025-6-6 10:31:59
 
  1.   
  2.     <label for="Admin-Image-img_cut" class="col-sm-2 col-md-1 col-lg-1  control-label">图片裁剪</label>
  3.    
  4.         
  5.         
  6.             <?php if(isset($data['img_url']) && $data['img_url']){echo '<img  id="img-cut" src="'.$data['img_url'].'">'; } ?>
  7.         
  8.         <input style="margin: 10px 0; width: 150%;" type="text" class="form-control" id="figure-img" name="figure_img" />
  9.         <input type="hidden" id="figure-type" name="figure_type" value="" />
  10.         <button type="button" id="save-cuted-img">确定裁剪</button>
  11.    
  12.   
复制代码
 
  1.     let $image = $('#img-cut');
  2.     $image.cropper({
  3.         viewMode: 1,
  4.         aspectRatio:600/400,
  5.         zoomable: false,
  6.         crop: function(event) { }
  7.     });
  8.     // Get the Cropper.js instance after initialized 有损压缩
  9.     let cropper = $image.data('cropper');
  10.     $('body').on('click', '#save-cuted-img', function(event) {
  11.         event.preventDefault();<br>     // 防止canvas数据量过大
  12.         cropper.getCroppedCanvas({ maxWidth: 2048, maxHeight: 2048 }).toBlob((blob) => {
  13.             const formData = new FormData();
  14.             formData.append('file', blob , 'croppedImage1.png');
  15.             $.ajax({
  16.                 type:"POST",
  17.                 url:"<?php echo U('Upload/ajax_file'); ?>",
  18.                 processData: false,
  19.                 contentType: false,
  20.                 data: formData,
  21.                 dataType: 'json',
  22.                 beforeSend: function () {
  23.                     $('#save-cuted-img').text('正在上传...').prop('disabled', true);
  24.                 },
  25.                 success: function(re){
  26.                     if (re.success) {
  27.                         $('#figure-img').val(re.msg);
  28.                         $('#figure-type').val($('#Admin-Image-type_id option:selected').text());
  29.                         alert("裁剪图片上传成功");
  30.                     } else {
  31.                         alert(re.msg);
  32.                     }
  33.                 },
  34.                 error() {
  35.                     console.log('裁剪图片上传失败');
  36.                 },
  37.                 complete: function () {
  38.                     $('#save-cuted-img').text('确定裁剪').prop('disabled', false);
  39.                 }
  40.             });
  41.         }, 'image/png', 1); // 设置图片质量
  42.     });
复制代码
 
 
 
来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

相关推荐

您需要登录后才可以回帖 登录 | 立即注册