vue实现图片截取上传

vue实现图片截取上传

结果

这是默认的
在这里插入图片描述
在这里插入图片描述

vue-cropper

pip install vue-cropper -s

Cropper组件

<template>
  <div :class="$options.name">
    <el-dialog
        style="margin-top: -50px"
        :visible.sync="dialogVisible"
        :close-on-click-modal="false"
        width="1000px"
        :before-close="handleClose">
      <div
          class="cropper-container">
        <div class="cropper-el">
          <vue-cropper
              ref="cropper"
              :img="cropperImg"
              :output-size="option.size"
              :output-type="option.outputType"
              :info="true"
              :full="option.full"
              :can-move="option.canMove"
              :can-move-box="option.canMoveBox"
              :fixed-box="option.fixedBox"
              :original="option.original"
              :auto-crop="option.autoCrop"
              :auto-crop-width="option.autoCropWidth"
              :auto-crop-height="option.autoCropHeight"
              :center-box="option.centerBox"
              :high="option.high"
              :info-true="option.infoTrue"
              @realTime="realTime"
              :enlarge="option.enlarge"
              :fixed="option.fixed"
              :fixed-number="fixedNumber"
          />
        </div>
        <!-- 预览 -->
        <div class="prive-el">
          <div class="prive-style">
            <div class="preview"
                 :style="previews.div">
              <img
                  :src="previews.url"
                  :style="previews.img">
            </div>
          </div>
          <el-button
              @click="uploadBth"
              v-if="option.img">重新上传
          </el-button>
        </div>
      </div>
      <span
          slot="footer"
          class="dialog-footer">
        <el-button
            @click="handleClose">取 消</el-button>
        <el-button
            type="primary"
            @click="saveImg">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {VueCropper} from 'vue-cropper';

export default {
  name: 'Cropper',
  components: {
    VueCropper
  },
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    imgType: {
      type: String,
      default: 'blob'
    },
    cropperImg: {
      type: String,
      default: ''
    },
    fixedNumber: {
      type:  Array,
      default: function () {
        return [1, 1];
      }
    }// 截图框的宽高比例
  },
  data() {
    return {
      previews: {},
      option: {
        img: '', // 裁剪图片的地址
        size: 1, // 裁剪生成图片的质量
        full: false, // 是否输出原图比例的截图 默认false
        outputType: 'jpg', // 裁剪生成图片的格式 默认jpg
        canMove: false, // 上传图片是否可以移动
        fixedBox: false, // 固定截图框大小 不允许改变
        original: false, // 上传图片按照原始比例渲染
        canMoveBox: true, // 截图框能否拖动
        autoCrop: true, // 是否默认生成截图框
        // 只有自动截图开启 宽度高度才生效
        autoCropWidth: 300 / this.fixedNumber[0] * this.fixedNumber[1], // 默认生成截图框宽度
        autoCropHeight: 300, // 默认生成截图框高度
        centerBox: true, // 截图框是否被限制在图片里面
        high: false, // 是否按照设备的dpr 输出等比例图片
        enlarge: 1, // 图片根据截图框输出比例倍数
        mode: 'contain', // 图片默认渲染方式
        maxImgSize: 2000, // 限制图片最大宽度和高度
        limitMinSize: [100, 100 / this.fixedNumber[0] * this.fixedNumber[1]], // 更新裁剪框最小属性
        infoTrue: false, // true 为展示真实输出图片宽高 false 展示看到的截图框宽高
        fixed: true, // 是否开启截图框宽高固定比例  (默认:true),
      }
    };
  },
  methods: {
    // 裁剪时触发的方法,用于实时预览
    realTime(data) {
      this.previews = data;
    },
    // 重新上传
    uploadBth() {
      this.$emit('update-cropper');
    },
    // 取消关闭弹框
    handleClose() {
      this.$emit('colse-dialog', false);
    },
    // 获取裁剪之后的图片,默认blob,也可以获取base64的图片
    saveImg() {
      if (this.imgType === 'blob') {
        this.$refs.cropper.getCropBlob(data => {
          this.$emit('upload-img', data);
        });
      } else {
        this.$refs.cropper.getCropData(data => {
          this.uploadFile = data;
          this.$emit('upload-img', data);
        });
      }
    }
  }
};
</script>

<style scoped>

.cropper-el {
  height: 450px;
  width: 450px;
}

.cropper-container {
  display: flex;
  justify-content: space-between;
}

.prive-el {
  flex: 1;
  text-align: center;
}

.prive-style {
  margin: 0 auto;
  flex: 1;
  -webkit-flex: 1;
  display: flex;
  display: -webkit-flex;
  justify-content: center;
  -webkit-justify-content: center;
  overflow: hidden;
  background-color: white;
  margin-left: 40px;
}

.preview {
  overflow: hidden;
}

.el-button {
  margin-top: 20px;
}
</style>

使用页

<template>
  <div>
    <el-form ref="form"  status-icon  label-width="80px" class="info">
      <el-row>
        <el-col :span="10" style="line-height: 178px; text-align: center">
          <el-form-item label="头像">
            <div class="avatar-uploader">
              <el-upload
                  :show-file-list="false"
                  :action="action"
                  :data="uploadData"
                  :on-change="selectChange"
                  :auto-upload="false"
                  :http-request="httpRequest">
                <img v-if="myFormData.headurl" :src="myFormData.headurl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
              <cropper
                  style="margin-top: -20px"
                  v-if="showCropper"
                  :dialog-visible="showCropper"
                  :cropper-img="cropperImg"
                  @update-cropper="updateCropper"
                  @colse-dialog="closeDialog"
                  @upload-img="uploadImg"/>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import Cropper from '../components/Cropper.vue';
import {upload} from "@/api/selfinfo";


export default {
  name: "selfinfo",
  components: {
    Cropper
  },
  data() {
    return {
      myFormData: {
        headurl: '',
      },
      uploadData: { // 上传需要的额外参数
        siteId: 1,
        source: 1,
        fileName: ''
      },
      action: 'https://jsonplaceholder.typicode.com/posts/', // 上传地址,必填
      cropperImg: '', // 需要裁剪的图片
      showCropper: false, // 是否显示裁剪框
      uploadFile: '', // 裁剪后的文件
    }
  },
  methods: {
    //图片上传
    httpRequest(request) {
      const { data, filename} = request;
      // 新建formDate对象
      let formData = new FormData();
      for (let key in data) {
        formData.append(key, data[key]);
      }
      // 文件单独push,第三个参数指定上传的文件名
      formData.append(filename, this.uploadFile, data.fileName);
    },
    // 选择文件
    selectChange(file) {
      const {raw, name} = file;
      this.openCropper(raw);
      this.uploadData.fileName = name;
    }, /**
     * @param {file} 上传的文件
     */
    openCropper(file) {
      var files = file;
      let isLt5M = files.size > (5 << 20);
      if (isLt5M) {
        this.$message.error('请上传5M内的图片');
        return false;
      }
      var reader = new FileReader();
      reader.onload = e => {
        let data;
        if (typeof e.target.result === 'object') {
          // 把Array Buffer转化为blob 如果是base64不需要
          data = window.URL.createObjectURL(new Blob([e.target.result]));
        } else {
          data = e.target.result;
        }
        this.cropperImg = data;
      };
      // 转化为base64
      // reader.readAsDataURL(file)
      // 转化为blob
      reader.readAsArrayBuffer(files);
      this.showCropper = true;
    },
    // 上传图片
    uploadImg: function (file) {
      this.uploadFile = file;
      //实际应用记得删除
      console.log(file)
      const param = new FormData();
      let fileType=file.type
      fileType=fileType.substr(fileType.lastIndexOf('/')+1)
      const imgName=new Date().getTime();
      console.log()
      param.append("file", file,imgName+"."+fileType)
      upload(param).then(resp => {
        console.log(resp);
        this.myFormData.headurl=resp.data;
      })
      this.closeDialog()
    },
    // 更新图片
    updateCropper() {
      this.$refs.fileUpload.$children[0].$el.click();
    },
    // 关闭窗口
    closeDialog() {
      this.showCropper = false;
    }
  },
}
</script>


<style scoped>
input[type="file"] {
  display: none !important;
}

.info {
  width: 1000px;
  margin: 0 auto;
  padding: 0;
}

.hide .el-upload--picture-card {
  display: none;
}

.avatar-uploader {
  /*border:1px dashed #000*/
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  width: 178px;
  height: 178px;
}

.avatar-uploader .el-upload {

  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

BeFondOfSunday

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值