美文网首页Vue
vue裁剪图片vue-cropper

vue裁剪图片vue-cropper

作者: 小哪吒 | 来源:发表于2020-04-09 11:22 被阅读0次

    安装

    npm install vue-cropper
    // 最好使用
    npm install vue-cropper@0.3.6
    

    如果使用vueCropper报错:Failed to mount component: template or render function not defined
    原因是vue-cropper新版本报错,最方便的解决办法是将vue-cropper降到旧版本,我使用的是0.3.6。

    npm uninstall vue-cropper
    npm install vue-cropper@0.3.6
    

    使用

    main.js里面

    import VueCropper from 'vue-cropper'
    Vue.use(VueCropper)
    

    组件内

    1、两种上传按钮

    <!-- element 上传图片按钮 -->
          <el-upload class="upload-demo" action="" drag 
    :auto-upload="false" :show-file-list="false" :on-change='changeUpload'>
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">点击上传</div>
            <div class="el-upload__tip">支持绝大多数图片格式,单张图片最大支持5MB</div>
          </el-upload>
    

    使用element-ui的上传按钮,要配置:auto-upload="false"(不要自动上传), :on-change='changeUpload'(选择完图片后的方法),一会儿再交代changeUpload方法

        <el-upload
            class="avatar-uploader"
            action=""
            :on-change="(file,filelist)=>onFileChange(file,filelist)"
            :show-file-list="false"
            :auto-upload="false"
            accept="image/*, .jpg, .png, .bmp"
          >
            <el-button type="primary" icon="el-icon-refresh-left">上传图片</el-button>
          </el-upload>
    

    2、设置一个弹出层,放剪裁图片的cropper

     <!-- vueCropper 剪裁图片实现-->
        <el-dialog title="图片剪裁" :visible.sync="dialogVisible" append-to-body>
          <div class="cropper-content">
            <div class="cropper" style="text-align:center">
            <vueCropper
                ref="cropper"
                :img="option.img"
                :outputSize="option.size"
                :outputType="option.outputType"
                :info="true"
                :full="option.full"
                :canMove="option.canMove"
                :canMoveBox="option.canMoveBox"
                :original="option.original"
                :autoCrop="option.autoCrop"
                :fixed="option.fixed"
                :fixedNumber="option.fixedNumber"
                :centerBox="option.centerBox"
                :infoTrue="option.infoTrue"
                :fixedBox="option.fixedBox"
                @realTime="realTime"
              ></vueCropper>
            </div>
          </div>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="finish" :loading="loading">确认</el-button>
          </div>
        </el-dialog>
    

    或者

    <el-dialog title="上传图片" :visible.sync="dialogVisible3" width="25%">
          <el-form :model="addForm">
            <div class="cropper-content" v-show="dialogVisible4">
              <div class="cropper" style="text-align:center">
                <vueCropper
                  ref="cropper"
                  :img="option.img"
                  :autoCrop="true"
                  :fixedNumber="[1, 1]"
                  :fixed="true"
                  :canScale="false"
                  :outputType="'png'"
                  :fixedBox="true"
                  :outputSize='1'
                  :maxImgSize='3000'
                  :full="true"
                ></vueCropper>
              </div>
            </div>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-upload
              class="avatar-uploader"
              action=""
              :on-change="(file,filelist)=>onFileChange(file,filelist)"
              :show-file-list="false"
              :auto-upload="false"
              accept="image/*, .jpg, .png, .bmp"
            >
              <el-button type="primary" icon="el-icon-refresh-left">上传图片</el-button>
            </el-upload>
            <el-button class="btnCus" icon="el-icon-check" @click="uploadImg" :loading="loadingImg">确认</el-button>
          </div>
        </el-dialog>
    
    

    3、剪裁框的样式

    // 截图
    .cropper-content {
        .cropper {
            width: auto;
            height: 300px;
        }
    }
    

    4、方法
    option是剪裁插件的属性配置,具体更多含义查看官网介绍,vue方式

    <script>
    import { client } from '@/utils/alioss'
    export default {
      data() {
        return {
          dialogVisible: false,
          // 裁剪组件的基础配置option
          option: {
            img: '', // 裁剪图片的地址
            info: true, // 裁剪框的大小信息
            outputSize: 0.8, // 裁剪生成图片的质量
            outputType: 'jpeg', // 裁剪生成图片的格式
            canScale: false, // 图片是否允许滚轮缩放
            autoCrop: true, // 是否默认生成截图框
            // autoCropWidth: 300, // 默认生成截图框宽度
            // autoCropHeight: 200, // 默认生成截图框高度
            fixedBox: true, // 固定截图框大小 不允许改变
            fixed: true, // 是否开启截图框宽高固定比例
            fixedNumber: [7, 5], // 截图框的宽高比例
            full: true, // 是否输出原图比例的截图
            canMoveBox: false, // 截图框能否拖动
            original: false, // 上传图片按照原始比例渲染
            centerBox: false, // 截图框是否被限制在图片里面
            infoTrue: true // true 为展示真实输出图片宽高 false 展示看到的截图框宽高
          },
          picsList: [],  //页面显示的数组
          // 防止重复提交
          loading: false
        }
      },
      methods: {
        // 上传按钮   限制图片大小
        changeUpload(file, fileList) {
          const isLt5M = file.size / 1024 / 1024 < 5
          if (!isLt5M) {
            this.$message.error('上传文件大小不能超过 5MB!')
            return false
          }
          this.fileinfo = file
    
          // 上传成功后将图片地址赋值给裁剪框显示图片
          this.$nextTick(() => {
            this.option.img = file.url
            this.dialogVisible = true
          })
        },
        // 点击裁剪,这一步是可以拿到处理后的地址
        finish() {
          this.$refs.cropper.getCropBlob((data) => {
            var fileName = 'goods' + this.fileinfo.uid
            this.loading = true
           //上传阿里云服务器
            client().put(fileName, data).then(result => {
              this.dialogVisible = false
              this.picsList.push(result.url)
            }).catch(err => {
              console.log(err)
              this.loading = false
            })
          })
        }
      }
    }
    </script>
    

    使用typescript下

    <script lang="ts">
    import VueCropper from 'vue-cropper'
    @Component({
        components: {
          VueCropper
        }
    })
    export default class CarManagePanel extends Vue {
      public fileinfo: any;
      public dialogVisible4: boolean = false;
      public option = {
        img: '', // 裁剪图片的地址
      }
      public addForm = {
        id: "",
        vehicleTypeName: "",
        imageUrl: "",
        file: "",
        attachmentName: ""
      };
      // 添加图片
      public onFileChange(e,list) {
        const isLt5M = e.size / 1024 / 1024 < 5
        if (!isLt5M) {
          this.$message.error('上传文件大小不能超过 5MB!')
          return false
        }
        this.fileinfo = e;
        let objectUrl = URL.createObjectURL(e.raw);
        // this.addForm.imageUrl = objectUrl;
        // this.addForm.file = e.raw;
        this.addForm.attachmentName = e.raw.name;
        // 上传成功后将图片地址赋值给裁剪框显示图片
        this.$nextTick(() => {
          this.option.img = objectUrl;
          this.dialogVisible4 = true;
        })
      }
    // 上传图片
      public async uploadImg() {
        let files = {};
        let objectUrl = '';
        this.$refs.cropper.getCropBlob(data => {
          files = new window.File([data], this.addForm.attachmentName, {type: data.type});
          aliupload().upload(files, this.addForm.attachmentName).then(res=>{
            if (res.res.statusCode == '200') {
              this.addForm.imageUrl = res.res.requestUrls[0].split('?')[0];
              this.loadingImg = false;
              this.dialogVisible3 = false;
              this.showDelete = true;
            } else {
              this.loadingImg = false;
              this.$message.warning('上传图片失败!')
            }
          })
        })
      }
    // 保存
      public saveForm() {
        if(this.addForm.id == ''){
          this.addVehicleType({
            vehicleTypeName: this.addForm.vehicleTypeName,
            vehicleImagePath: this.addForm.imageUrl
          }).then(res=>{
            this.addFormVisible = false;
            this.$message({ message: '添加成功', type: 'success' });
          })
        }else{
          this.editVehicleType({
            id: this.addForm.id,
            vehicleTypeName: this.addForm.vehicleTypeName,
            vehicleImagePath: this.addForm.imageUrl
          }).then(res=>{
            this.addFormVisible = false;
            this.$message({ message: '修改成功', type: 'success' });
          })
        }
        this.$emit("road");
      }
    }
    </script>
    

    相关文章

      网友评论

        本文标题:vue裁剪图片vue-cropper

        本文链接:https://www.haomeiwen.com/subject/livqmhtx.html