1. 90前端首页
  2. 前端框架

vue+apiclound + cropper.js 完成上传+裁剪+压缩图片

直接上代码,很多都有注释

思路:用apiclound 先拉起相机和相册 ,然后获取图片后,根据宽度(targetWidth 这个参数)进行压缩 ,使用cropper.js进行裁剪压缩后的图片。
最后获取裁剪的图片上传的服务器,拿到服务器返回的地址,在回显到本地预览。
可以把代码直接复制到本地,以一个组件的形式测试。
`

<template>
  <div id=\"demo\">
    <!-- 遮罩层 -->
    <div class=\"v-simple-cropper\">
      <div class=\"v-cropper-layer\" ref=\"layer\">
        <div class=\"layer-header dis-flex flex-center flex-pack-center flex-pack-justify\">
          <button class=\"cancel\" @click=\"cancelHandle\">取消</button>
          <button class=\"confirm\" @click=\"crop\">确定</button>
        </div>
        <img ref=\"cropperImg\">
      </div>
    </div>
    <div>
      <div class=\"show \" @click=\"uploadHeadPic\">
        <div class=\"uploadpic\" v-if=\"isShow\">
          <img src=\"../assets/images/tournaments/add.png\" alt=\"\">
          <span></span>
          <div>
            <p>点击上传赛事主题背景</p>
            <p class=\"det\">(图片大小:15M 以内)</p>
          </div>
        </div>
        <div class=\"picture\" :style=\"\'backgroundImage:url(\'+spreadPic+\')\'\" v-if=\'spreadPic\'></div>
        <div class=\"picture\" :style=\"\'backgroundImage:url(\'+headerImage+\')\'\" v-else></div>
      </div>
      <div>
        <input class=\"file\" ref=\"file\" type=\"file\" accept=\"image/*\" style=\"display:none\" @change=\"change\">

      </div>
    </div>
  </div>
</template>

<script>
import Cropper from \'cropperjs\'
export default {
  props: [\'getPortpic\'],
  data () {
    return {
      headerImage: \'\',
      picValue: \'\',
      croppable: false,
      url: \'\',
      isShow: true,
      spreadPic: \'\',
      imgPath: \'\',//获取的图片地址
      domain: \'\',//拿到的域名
      cropper: {},
      filename: \'\'
    }
  },
  created () {
  },
  mounted () {
    //拿到背景图渲染
    if (!!this.getPortpic) {
      this.spreadPic = this.getPortpic
      this.isShow = false
      console.log(\'我拿到了接口的图片啊===》\', this.spreadPic);
    } else if (this.imgPath && this.domain) {
      this.spreadPic = this.domain + this.imgPath
      this.isShow = false
    } else {
    }

    //初始化这个裁剪框
    var self = this;
    // var image = document.getElementById(\'image\');
    let image = this.$refs[\'cropperImg\']
    this.cropper = new Cropper(image, {
      // aspectRatio: 16 / 5,
      viewMod: 1,//3只能在2内移动。
      dragMode: \"move\",
      cropBoxMovable: false,
      cropBoxResizable: false,
      aspectRatio: 359 / 154,
      ready: function () {
        self.croppable = true;
      },
      zoom: function (event) {
        console.log(event.type, event.detail.ratio);
      },
    });

  },
  methods: {
    uploadHeadPic () {  //呼出相机和相册
      let that = this
      api.actionSheet({
        title: \'上传照片\',
        cancelTitle: \'取消\',
        buttons: [\'拍照\', \'手机相册\']
      }, function (ret, err) {
        if (ret) {
          if (ret.buttonIndex == 1) {
            api.getPicture({
              sourceType: \'camera\',
              encodingType: \'jpg\',
              mediaValue: \'pic\',
              destinationType: \'base64\',
              quality: 100,
              targetWidth: 1000, //宽度压缩
              allowEdit: false,
              saveToPhotoAlbum: false
            }, function (ret, err) {
              if (ret) {
                // 保存图片然后调用裁剪的窗口
                that.change(ret.data)
              } else {
                api.toast({
                  msg: \'图像获取失败\',
                  duration: 1000,
                  location: \'bottom\'
                });
              }
            });
          } else if (ret.buttonIndex == 2) {
            //手机相册选图片
            api.getPicture({
              sourceType: \'library\',
              encodingType: \'png\',
              mediaValue: \'pic\',
              destinationType: \'base64\',
              allowEdit: false,
              quality: 100,
              targetWidth: 1000,
              preview: true,
              saveToPhotoAlbum: false
            }, function (ret, err) {
              // alert(JSON.stringify(ret.data));
              if (ret) {
                that.change(ret.data)
                // 调用裁剪的窗口
              } else {
                api.toast({
                  msg: \'图像获取失败\',
                  duration: 1000,
                  location: \'bottom\'
                });
              }
            });
          }
        }
      });
    },
    saveImg (path) {
      api.showProgress({
        title: \'...上传中...\',
      });
      console.log(\'=======上传的base64=====>\', path);
      this.$axios(
        this.httpUploadImgUrl + this.afterurl.UploadBase64,
        { image: path },
        \'post\'
      ).then((res) => {
        if (res.data.code == 200) {
          this.domain = res.data.data.domain
          this.imgPath = res.data.data.path
          this.$emit(\'getImgPath\', this.imgPath)  //拿到图片传递给父组件
          api.hideProgress(); //隐藏上传进度条
          api.toast({
            msg: \'上传成功\',
            duration: 1000,
            location: \'bottom\'
          })
          this.spreadPic = this.domain + this.imgPath
          this.isShow = false
          this.cancelHandle()
        
          this.$emit(\'getImgPath\', this.imgPath)  //传递给父组件
        } else {
        
          api.toast({
            msg: \'图像上传失败\',
            duration: 1000,
            location: \'bottom\'
          });
          console.log(\'失败啦\', res.data.code)
        }
      }).catch((err) => {
        api.toast({
          msg: \'出错啦\',
          duration: 1000,
          location: \'bottom\'
        });
      })
    },


    change (pathData) { //获取图片路径 调用裁剪面板
      // 拿到图片
      this.picValue = pathData;
      //每次替换图片要重新得到新的url
      if (this.cropper) {
        this.cropper.replace(this.picValue);
      }
      this.$refs[\'layer\'].style.display = \'block\'

    },

    getObjectURL (file) {
      var url = null;
      if (window.createObjectURL != undefined) { // basic
        url = window.createObjectURL(file);
      } else if (window.URL != undefined) { // mozilla(firefox)
        url = window.URL.createObjectURL(file);
      } else if (window.webkitURL != undefined) { // webkit or chrome
        url = window.webkitURL.createObjectURL(file);
      }
      return url;
    },

    crop () {  //裁剪图
      let croppedCanvas;
      let roundedCanvas;
      if (!this.croppable) {
        return;
      }
      // Crop

      croppedCanvas = this.cropper.getCroppedCanvas();
      console.log(this.cropper.crossOriginUrl)
      // Round
      roundedCanvas = this.getRoundedCanvas(croppedCanvas);
      this.headerImage = roundedCanvas.toDataURL(\'image/jpeg\', 0.7);

      this.saveImg(this.headerImage.toString())
    },
    // 取消上传
    cancelHandle () {
      this.cropper.reset()
      this.$refs[\'layer\'].style.display = \'none\'
      this.$refs[\'file\'].value = \'\'
    },

    //canvers  画图
    getRoundedCanvas (sourceCanvas) {
      var canvas = document.createElement(\'canvas\');
      var context = canvas.getContext(\'2d\');
      var width = sourceCanvas.width;
      var height = sourceCanvas.height;
      canvas.width = width;
      canvas.height = height;
      context.drawImage(sourceCanvas, 0, 0, width, height);
      context.globalCompositeOperation = \'destination-in\';
      context.beginPath();
      context.fill();
      return canvas;
    },
    reset () {
      this.cropper.zoomTo(1);
    },

  }
}
</script>

<style lang=\'scss\'>
* {
  margin: 0;
  padding: 0;
}

.uploadpic {
  width: 100%;
  height: 241px;
  background-color: #fff;
  border-radius: 30px;
  margin-bottom: 19px;
  position: relative;
  overflow: hidden;
  img {
    width: 47px;
    height: 47px;
    position: absolute;
    top: 75px;
    left: 359px;
  }
  p {
    font-family: \"MicrosoftYaHeiLight [Light]\";
    font-size: 25px;
    position: absolute;
    left: 265px;
    bottom: 45px;
    color: #3c3c43;
  }
  .det {
    bottom: 10px;
    color: rgba($color: #3c3c43, $alpha: 0.6);
  }
}
#demo #button {
  position: absolute;
  right: 10px;
  top: 10px;
  width: 80px;
  height: 40px;
  border: none;
  border-radius: 5px;
  background: white;
}

#demo #button1 {
  position: absolute;
  right: 100px;
  top: 10px;
  width: 80px;
  height: 40px;
  border: none;
  border-radius: 5px;
  background: white;
}

#demo .show {
  // width: 772px;
  height: 241px;
  background-color: #fff;
  border-radius: 30px;
  margin-bottom: 19px;
  position: relative;
  overflow: hidden;
}

#demo .picture {
  width: 100%;
  height: 100%;
  overflow: hidden;
  background-position: center center;
  background-repeat: no-repeat;
  background-size: cover;
}

#demo .picture {
  border-radius: 0% !important;
}

#demo .container {
  z-index: 99;
  position: fixed;
  padding-top: 60px;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
}

#demo #image {
  max-width: 100%;
}

.cropper-view-box,
.cropper-face {
  /* border-radius: 50%; */
}

.cropper-container {
  font-size: 0;
  line-height: 0;

  position: relative;

  -webkit-user-select: none;

  -moz-user-select: none;

  -ms-user-select: none;

  user-select: none;

  direction: ltr;
  -ms-touch-action: none;
  touch-action: none;
}

.cropper-container img {
  /* Avoid margin top issue (Occur only when margin-top <= -height) */
  display: block;
  min-width: 0 !important;
  max-width: none !important;
  min-height: 0 !important;
  max-height: none !important;
  width: 100%;
  height: 100%;
  image-orientation: 0deg;
}

.cropper-wrap-box,
.cropper-canvas,
.cropper-drag-box,
.cropper-crop-box,
.cropper-modal {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}

.cropper-wrap-box {
  overflow: hidden;
}

.cropper-drag-box {
  opacity: 0;
  background-color: #fff;
}

.cropper-modal {
  opacity: 0.5;
  background-color: #000;
}

.cropper-view-box {
  display: block;
  overflow: hidden;

  width: 100%;
  height: 100%;

  outline: 1px solid #39f;
  outline-color: rgba(51, 153, 255, 0.75);
}

.cropper-dashed {
  position: absolute;

  display: block;

  opacity: 0.5;
  border: 0 dashed #eee;
}

.cropper-dashed.dashed-h {
  top: 33.33333%;
  left: 0;
  width: 100%;
  height: 33.33333%;
  border-top-width: 1px;
  border-bottom-width: 1px;
}

.cropper-dashed.dashed-v {
  top: 0;
  left: 33.33333%;
  width: 33.33333%;
  height: 100%;
  border-right-width: 1px;
  border-left-width: 1px;
}

.cropper-center {
  position: absolute;
  top: 50%;
  left: 50%;

  display: block;

  width: 0;
  height: 0;

  opacity: 0.75;
}

.cropper-center:before,
.cropper-center:after {
  position: absolute;
  display: block;
  content: \" \";
  background-color: #eee;
}

.cropper-center:before {
  top: 0;
  left: -3px;
  width: 7px;
  height: 1px;
}

.cropper-center:after {
  top: -3px;
  left: 0;
  width: 1px;
  height: 7px;
}

.cropper-face,
.cropper-line,
.cropper-point {
  position: absolute;

  display: block;

  width: 100%;
  height: 100%;

  opacity: 0.1;
}

.cropper-face {
  top: 0;
  left: 0;

  background-color: #fff;
}

.cropper-line {
  background-color: #39f;
}

.cropper-line.line-e {
  top: 0;
  right: -3px;
  width: 5px;
  cursor: e-resize;
}

.cropper-line.line-n {
  top: -3px;
  left: 0;
  height: 5px;
  cursor: n-resize;
}

.cropper-line.line-w {
  top: 0;
  left: -3px;
  width: 5px;
  cursor: w-resize;
}

.cropper-line.line-s {
  bottom: -3px;
  left: 0;
  height: 5px;
  cursor: s-resize;
}

.cropper-point {
  width: 5px;
  height: 5px;

  opacity: 0.75;
  background-color: #39f;
}

.cropper-point.point-e {
  top: 50%;
  right: -3px;
  margin-top: -3px;
  cursor: e-resize;
}

.cropper-point.point-n {
  top: -3px;
  left: 50%;
  margin-left: -3px;
  cursor: n-resize;
}

.cropper-point.point-w {
  top: 50%;
  left: -3px;
  margin-top: -3px;
  cursor: w-resize;
}

.cropper-point.point-s {
  bottom: -3px;
  left: 50%;
  margin-left: -3px;
  cursor: s-resize;
}

.cropper-point.point-ne {
  top: -3px;
  right: -3px;
  cursor: ne-resize;
}

.cropper-point.point-nw {
  top: -3px;
  left: -3px;
  cursor: nw-resize;
}

.cropper-point.point-sw {
  bottom: -3px;
  left: -3px;
  cursor: sw-resize;
}

.cropper-point.point-se {
  right: -3px;
  bottom: -3px;
  width: 20px;
  height: 20px;
  cursor: se-resize;
  opacity: 1;
}

@media (min-width: 768px) {
  .cropper-point.point-se {
    width: 15px;
    height: 15px;
  }
}

@media (min-width: 992px) {
  .cropper-point.point-se {
    width: 10px;
    height: 10px;
  }
}

@media (min-width: 1200px) {
  .cropper-point.point-se {
    width: 5px;
    height: 5px;
    opacity: 0.75;
  }
}

.cropper-point.point-se:before {
  position: absolute;
  right: -50%;
  bottom: -50%;
  display: block;
  width: 200%;
  height: 200%;
  content: \" \";
  opacity: 0;
  background-color: #39f;
}

.cropper-invisible {
  opacity: 0;
}

.cropper-bg {
  background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAAA3NCSVQICAjb4U/gAAAABlBMVEXMzMz////TjRV2AAAACXBIWXMAAArrAAAK6wGCiw1aAAAAHHRFWHRTb2Z0d2FyZQBBZG9iZSBGaXJld29ya3MgQ1M26LyyjAAAABFJREFUCJlj+M/AgBVhF/0PAH6/D/HkDxOGAAAAAElFTkSuQmCC\");
}

.cropper-hide {
  position: absolute;

  display: block;

  width: 0;
  height: 0;
}

.cropper-hidden {
  display: none !important;
}

.cropper-move {
  cursor: move;
}

.cropper-crop {
  cursor: crosshair;
}

.cropper-disabled .cropper-drag-box,
.cropper-disabled .cropper-face,
.cropper-disabled .cropper-line,
.cropper-disabled .cropper-point {
  cursor: not-allowed;
}

.file {
  display: none;
}
.v-cropper-layer {
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  z-index: 99999;
  display: none;
  .layer-header {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 99999;
    background: #fff;
    width: 100%;
    height: 0.8rem;
    padding: 0 0.2rem;
    box-sizing: border-box;
  }
  .cancel,
  .confirm {
    line-height: 70px;
    font-size: 30px;
    background: inherit;
    border: 0;
    outline: 0;
    float: left;
    width: 110px;
    height: 70px;
    background-color: rgb(53, 199, 90);
    border-radius: 10px;
    color: #fff;
  }
  .cancel {
    background-color: #7e7e80;
  }

  img {
    position: inherit !important;
    border-radius: inherit !important;
    float: inherit !important;
  }
}
#demo /deep/ .cropper-modal {
  opacity: 0.3 !important;
}
#demo /deep/ .cropper-bg {
  background: #000 !important;
}
#demo /deep/ .cropper-view-box {
  outline: 1px solid #fff !important;
  outline-color: #fff !important;
}
</style>

`

注意:我在测试的时候,没有弄清除targetWidth 他的压缩规则,看别人的帖子说值在800-1000比较正常,值越大越清晰。所以质量也会大一点,我设置到1000压缩效果还是很好的,基本大小控制在原图的四分之一左右,看着也不算模糊

本文来自网络整理,转载请注明原出处:https://segmentfault.com/a/1190000022055851

展开阅读全文

发表评论

登录后才能评论