vue3+ elementui+canvas 实现压缩图片

<template>
  <div>
    <el-upload
      class="upload-demo"
      action=""
      :show-file-list="false"
      :before-upload="beforeUpload"
      :on-success="handleSuccess"
    >
      <el-button size="small" type="primary">点击上传图片</el-button>
    </el-upload>

    <canvas ref="canvas" style="display: none;"></canvas>

    <el-image
      v-if="imageUrl"
      :src="imageUrl"
      style="max-width: 300px; margin-top: 20px;"
    ></el-image>
  </div>
</template>

<script>
export default {
  data() {
    return {
      imageUrl: null,
    };
  },
  methods: {
    beforeUpload(file) {
      return new Promise((resolve) => {
        this.compressImage(file)
          .then((compressedFile) => {
            resolve(compressedFile);
          })
          .catch((error) => {
            console.error('图片压缩失败:', error);
            resolve(false);
          });
      });
    },
    handleSuccess(response) {
      // 处理上传成功后的操作,这里省略具体代码
      console.log('上传成功', response);
    },
    compressImage(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = (e) => {
          const image = new Image();
          image.onload = () => {
            const canvas = this.$refs.canvas;
            const ctx = canvas.getContext('2d');
            const maxSize = 800; // 设置最大宽高,根据需要调整
            let width = image.width;
            let height = image.height;

            if (width > height) {
              if (width > maxSize) {
                height *= maxSize / width;
                width = maxSize;
              }
            } else {
              if (height > maxSize) {
                width *= maxSize / height;
                height = maxSize;
              }
            }

            canvas.width = width;
            canvas.height = height;

            ctx.drawImage(image, 0, 0, width, height);

            canvas.toBlob(
              (blob) => {
                const compressedFile = new File([blob], file.name, {
                  type: file.type,
                  lastModified: file.lastModified,
                });
                resolve(compressedFile);
              },
              file.type,
              0.7 // 0.7表示压缩质量,可以根据需要调整
            );
          };
          image.src = e.target.result;
        };
        reader.readAsDataURL(file);
      });
    },
  },
};
</script>

<style>
.upload-demo {
  border: 1px dashed #409eff;
  border-radius: 6px;
  padding: 20px;
  text-align: center;
  cursor: pointer;
}
</style>

在上传之前,通过before-upload属性调用beforeUpload方法,该方法使用Canvas对图片进行压缩。在compressImage方法中,我们读取用户选择的图片,绘制到Canvas上并调整尺寸,然后使用canvas.toBlob()将Canvas中的图片导出为Blob对象,最后将Blob对象封装为一个新的File对象,将其传递给before-upload方法,实现图片压缩

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值