图片上传组件+图片压缩

<template>
  <div class="component-upload-image">
    <el-upload
      multiple
      :action="uploadImgUrl"
      list-type="picture-card"
      :on-success="handleUploadSuccess"
      :before-upload="handleBeforeUpload"
      :limit="limit"
      :on-error="handleUploadError"
      :on-exceed="handleExceed"
      name="file"
      :on-remove="handleRemove"
      :show-file-list="true"
      :headers="headers"
      :file-list="fileList"
      :on-preview="handlePictureCardPreview"
      :class="{ hide: this.fileList.length >= this.limit }"
      :disabled="disabled"
    >
      <i class="el-icon-plus"></i>
    </el-upload>

    <!-- 上传提示 -->
    <div class="el-upload__tip" slot="tip" v-if="showTip">
      请上传
      <template v-if="fileSize">
        大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b>
      </template>
      <template v-if="fileType">
        格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b>
      </template>
      的文件
    </div>

    <el-dialog
      :visible.sync="dialogVisible"
      title="预览"
      width="800"
      append-to-body
    >
      <img
        :src="dialogImageUrl"
        style="display: block; max-width: 100%; margin: 0 auto"
      />
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";

export default {
  props: {
    value: [String, Object, Array],
    // 图片数量限制
    limit: {
      type: Number,
      default: 5,
    },
    // 是否禁用
    disabled: {
      type: Boolean,
      default: false,
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 5,
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ["png", "jpg", "jpeg"],
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      number: 0,
      uploadList: [],
      dialogImageUrl: "",
      dialogVisible: false,
      hideUpload: false,
      baseUrl: process.env.VUE_APP_BASE_API,
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      fileList: [],
    };
  },
  watch: {
    value: {
      handler(val) {
        console.log("11111", this.fileList);
        if (val) {
          // 首先将值转为数组
          const list = Array.isArray(val) ? val : this.value.split(",");
          // console.log("list", list);
          // console.log('this.baseUrl',this.baseUrl);
          // 然后将数组转为对象数组
          this.fileList = list.map((item) => {
            // console.log("typeof item", typeof item);
            if (typeof item === "string") {
              if (item.indexOf(this.baseUrl) == -1) {
                // console.log("第一步");
                item = { name: this.baseUrl + item, url: this.baseUrl + item };
              } else {
                // console.log("第二步");
                item = { name: item, url: item };
              }
            } else {
              // console.log("不是string", item);
              if (item.url.indexOf(this.baseUrl) == -1) {
                // console.log("第一步");
                item.url = this.baseUrl + item.url;
              } else {
                // console.log("第二步");
                item.url = item.url;
              }
              // item.url = this.baseUrl + item.url;
            }
            return item;
          });
          // console.log("22222", this.fileList);
        } else {
          this.fileList = [];
          return [];
        }
      },
      deep: true,
      immediate: true,
    },
  },
  computed: {
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize);
    },
  },
  methods: {
    // 删除图片
    handleRemove(file, fileList) {
      // console.log(file);
      // console.log(fileList);
      // return
      const findex = this.fileList.map((f) => f.name).indexOf(file.name);
      if (findex > -1) {
        this.fileList.splice(findex, 1);
        this.$emit("input", this.listToString(this.fileList));
      }
    },
    // 上传成功回调
    handleUploadSuccess(res) {
      this.uploadList.push({ name: res.fileName, url: res.fileName });
      if (this.uploadList.length === this.number) {
        this.fileList = this.fileList.concat(this.uploadList);
        this.uploadList = [];
        this.number = 0;
        this.$emit("input", this.listToString(this.fileList));
        this.$modal.closeLoading();
      }
    },
    // 上传前loading加载
    handleBeforeUpload(file) {
      const _this = this;
      let Orientation;
      let ndata;
      let isImg = false;
      if (this.fileType.length) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        isImg = this.fileType.some((type) => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
      } else {
        isImg = file.type.indexOf("image") > -1;
      }

      if (!isImg) {
        this.$modal.msgError(
          `文件格式不正确, 请上传${this.fileType.join("/")}图片格式文件!`
        );
        return false;
      }
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$modal.msgError(`上传头像图片大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      this.$modal.loading("正在上传图片,请稍候...");
      this.number++;
      //小于1M,不压缩
      console.log(file.size, "this.fileSize");
      if (file.size > 1 * 1024 * 1024) {
        return new Promise((resolve) => {
          // 反之压缩图片
          const reader = new FileReader();
          // 将图片2将转成 base64 格式
          reader.readAsDataURL(file);
          // console.log(reader)
          // 读取成功后的回调
          reader.onloadend = function () {
            const result = this.result;
            const img = new Image();
            img.src = result;
            img.onload = function () {
              // const data = _this.compress(img, Orientation)
              // // _this.headerImage = data
              ndata = _this.compress(img, Orientation);
              // BASE64转图片
              let arr = ndata.split(","),
                mime = arr[0].match(/:(.*?);/)[1],
                bstr = atob(arr[1]),
                n = bstr.length,
                u8arr = new Uint8Array(n);
              while (n--) {
                u8arr[n] = bstr.charCodeAt(n);
              }
              const blobData = _this.dataURItoBlob(ndata, file.type);
              resolve(blobData);
            };
          };

          //   const reader = new FileReader();
          //   const image = new Image();
          //   image.onload = (imageEvent) => {
          //     const canvas = document.createElement("canvas");
          //     const context = canvas.getContext("2d");
          //     const width = image.width * 0.5; //宽缩一半
          //     const height = image.height * 0.5; //高缩一半
          //     canvas.width = width;
          //     canvas.height = height;
          //     context.clearRect(0, 0, width, height);
          //     context.drawImage(image, 0, 0, width, height);
          //     const dataUrl = canvas.toDataURL(file.type);
          //     const blobData = _this.dataURItoBlob(dataUrl, file.type);
          //     resolve(blobData);
          //   };
          //   reader.onload = (e) => {
          //     image.src = e.target.result;
          //   };

          //   reader.readAsDataURL(file);
        });
      }
    },
    dataURItoBlob(dataURI, type) {
      var binary = atob(dataURI.split(",")[1]);
      var array = [];
      for (var i = 0; i < binary.length; i++) {
        array.push(binary.charCodeAt(i));
      }
      return new Blob([new Uint8Array(array)], { type: type });
    },
    // 文件个数超出
    handleExceed() {
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    // 上传失败
    handleUploadError() {
      this.$modal.msgError("上传图片失败,请重试");
      this.$modal.closeLoading();
    },
    // 预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 对象转成指定字符串分隔
    listToString(list, separator) {
      console.log(list);
      let strs = [];
      // separator = separator || ",";
      for (let i in list) {
        strs.push(list[i].url.replace(this.baseUrl, ""));
        // strs += list[i].url.replace(this.baseUrl, "") + separator;
      }
      console.log(strs);
      // return strs != '' ? strs.substr(0, strs.length - 1) : '';
      return strs;
    },
    compress(img, Orientation) {
      const canvas = document.createElement("canvas");
      const ctx = canvas.getContext("2d");
      // 瓦片canvas
      const tCanvas = document.createElement("canvas");
      const tctx = tCanvas.getContext("2d");
      const initSize = img.src.length;
      let width = img.width;
      let height = img.height;
      // 如果图片大于四百万像素,计算压缩比并将大小压至400万以下
      let ratio;
      if ((ratio = (width * height) / 15000000) > 1) {
        console.log("大于400万像素");
        ratio = Math.sqrt(ratio);
        width /= ratio;
        height /= ratio;
      } else {
        ratio = 1;
      }
      canvas.width = width;
      canvas.height = height;
      //        铺底色
      ctx.fillStyle = "#fff";
      ctx.fillRect(0, 0, canvas.width, canvas.height);
      // 如果图片像素大于100万则使用瓦片绘制
      let count;
      if ((count = (width * height) / 1000000) > 1) {
        console.log("超过100W像素");
        count = ~~(Math.sqrt(count) + 1); // 计算要分成多少块瓦片
        //            计算每块瓦片的宽和高
        const nw = ~~(width / count);
        const nh = ~~(height / count);
        tCanvas.width = nw;
        tCanvas.height = nh;
        for (let i = 0; i < count; i++) {
          for (let j = 0; j < count; j++) {
            tctx.drawImage(
              img,
              i * nw * ratio,
              j * nh * ratio,
              nw * ratio,
              nh * ratio,
              0,
              0,
              nw,
              nh
            );
            ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh);
          }
        }
      } else {
        ctx.drawImage(img, 0, 0, width, height);
      }
      // 进行最小压缩
      const ndata = canvas.toDataURL("image/jpeg", 0.1);

      // console.log('压缩前:' + initSize)
      // console.log('压缩后:' + ndata.length)
      // console.log('ndata:' + ndata)

      console.log(
        "压缩率:" + ~~((100 * (initSize - ndata.length)) / initSize) + "%"
      );
      tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0;

      return ndata;
    },
  },
};
</script>
<style scoped lang="scss">
// .el-upload--picture-card 控制加号部分
::v-deep.hide .el-upload--picture-card {
  display: none;
}
// 去掉动画效果
::v-deep .el-list-enter-active,
::v-deep .el-list-leave-active {
  transition: all 0s;
}

::v-deep .el-list-enter,
.el-list-leave-active {
  opacity: 0;
  transform: translateY(0);
}
</style>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容