h5页面上传图片

1 HTML

<van-uploader v-model="content" :before-read="(file) => beforeRead(content, file)" max-count="6" multiple />

2 JS

let content = ref([])
const beforeRead = (arr, file) => {
  if (file.length) {
    file.forEach((item) => {
      imgCompress(item, (res) => {
        arr.push({ file: item, url: res });
      });
    });
  } else {
    imgCompress(file, (res) => {
      arr.push({ file, url: res });
    });
  }
}

function getBase64(file) {
  // 上传图片转换base64
  return new Promise(function (resolve, reject) {
    let reader = new FileReader();

    let imgResult = "";
    reader.readAsDataURL(file);
    reader.onload = function () {
      imgResult = reader.result;
    };
    reader.onerror = function (error) {
      reject(error);
    };
    reader.onloadend = function () {
      resolve(imgResult);
    };
  });
}

function drawBeauty(beauty, width = 100, height = 100, fun) {
  const imgWidth = width
  const imgHeight = height
  const canEle = document.createElement('canvas')
  canEle.id = 'canvas'
  canEle.setAttribute("hidden", true);
  document.body.append(canEle)
  var canvas = document.getElementById("canvas");
  canvas.width = imgWidth
  canvas.height = imgHeight
  var ctx = canvas.getContext("2d");
  ctx.drawImage(beauty, 0, 0, imgWidth, imgHeight);
  const blob = canvas.toDataURL('image/jpeg', .75)
  fun(blob)
  // document.getElementById('img').src = blob
}

async function imgCompress(imgURI, fn) { // 图片压缩 imgURI:base64
  // if( !/image/g.test(imgURI) ) return fn(imgURI); // 如果不是image
  var beauty = new Image();

  if (imgURI instanceof File)
    beauty.src = await getBase64(imgURI);
  if (beauty.complete) {
    drawBeauty(beauty, beauty.width, beauty.height, fn);
  } else {
    beauty.onload = function () {
      const value = drawBeauty(beauty, beauty.width, beauty.height, fn);
    };
    beauty.onerror = function () {
      window.alert('图片加载失败,请重试');
    };
  };
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值