zl程序教程

您现在的位置是:首页 >  前端

当前栏目

vue:前端压缩图片上传

Vue上传前端 图片 压缩
2023-09-11 14:22:28 时间

网上关于vue前端压缩图片后再上传到的代码很多,大家可以一试~

compressImage.js文件

// 压缩图片
export function compressImage({ file, config = {}, fileName }) {
    const read = new FileReader()
    read.readAsDataURL(file)
    return new Promise(function (resolve) {
        read.onload = function (e) {
            let img = new Image()
            img.src = e.target.result
            img.onload = function () {
                // 默认按比例压缩
                let w = config.width || img.width
                let h = config.height || img.height
                // 生成canvas
                let canvas = document.createElement('canvas')
                let ctx = canvas.getContext('2d')
                let base64
                // 创建属性节点
                canvas.setAttribute('width', w)
                canvas.setAttribute('height', h)
                ctx.drawImage(this, 0, 0, w, h)
                base64 = canvas.toDataURL(file['type'], config.quality || 0.5)
                let finalFile = dataURLtoFile(base64, fileName)
                let fileBinary = dataURLtoBlob(base64, fileName)
                resolve({ finalFile, fileBinary })
            }
        }
    })
}
// 将base64转为二进制
function dataURLtoBlob(dataurl, fileName) {
    let arr = dataurl.split(',')
    let mime = arr[0].match(/:(.*?);/)[1]
    let bstr = atob(arr[1])
    let n = bstr.length
    let u8arr = new Uint8Array(n)
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
    }
    let blobObj = new Blob([u8arr], { type: mime })
    return {
        fileName,
        blobUrl: URL.createObjectURL(blobObj)
    }
}

// 将base64编码转回file文件  
function dataURLtoFile(dataurl, fileName) {
    let arr = dataurl.split(',')
    let mime = arr[0].match(/:(.*?);/)[1]
    let bstr = atob(arr[1])
    let n = bstr.length
    let u8arr = new Uint8Array(n)
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
    }
    let file = new File([u8arr], { type: mime })
    return {
        fileName,
        file
    }
}

页面调用

<template>
  <div>
    <el-upload
      action="#"
      multiple
      accept="image/jpg,image/jpeg,image/png"
      list-type="picture-card"
      :on-change="fileChange"
      :auto-upload="false"
    >
    </el-upload>
    <el-button type="primary" @click="compressFile">压缩</el-button>
    <div>
      <el-image
        v-for="(item, index) in imageList"
        :key="index"
        fit="cover"
        style="width: 300px; height: 300px"
        :src="item.fileBinary.blobUrl"
        :preview-src-list="srcList"
      ></el-image>
    </div>
  </div>
</template>

<script>
import { compressImage } from "./compressImage";
export default {
  data() {
    return {
      fileList: [],
      imageList: [],
      srcList: [],
    };
  },
  methods: {
    fileChange(file, fileList) {
      this.fileList = fileList;
    },
    compressFile() {
      let config = {
        quality: 0.5, //默认0.5  0-1
        // width:100,
        // height:100
      };
      this.fileList.forEach(async (item) => {
        console.log("原图size===>", item.size);
        let result = await compressImage({
          file: item.raw,
          config,
          fileName: item.name,
        });
        console.log("压缩后图片size===>", result.finalFile.file.size);
        this.imageList.push(result);
        this.srcList.push(result.fileBinary.blobUrl);
      });
      console.log("压缩后图片===>", this.imageList);
    },
  },
};
</script>

演示结果

 

 示例代码地址

压缩图片示例icon-default.png?t=M0H8https://gitee.com/qianjue520/compress-vue