uniapp 开发小程序压缩图片

文章内容包含:文件转base64、base64转文件、获取文件尺寸、压缩图片(微信小程序及js)。

uniapp 小程序压缩图片

小程序压缩图片和普通 html 压缩图片思路一致。

步骤为:

  1. 获取图片信息
  2. 获取canvas 节点
  3. 创建图片对象
  4. 压缩图片

详细代码

/**
 * 获取图片信息
 * @param {string} imgObj 图片对象path
 * @param {function} fn 回调函数
 * @returns {ojbect} cbParams 
 * {
 *  height: 722,
 *  width: 1366,
 *  type: \'png\',
 *  path: \'\',
 *  orientation: \'up\',
 *  errMsg: \'\'
 * }
 */
function getImageObject (src, fn) {
  uni.getImageInfo({
    src: src,
    success (res) {
      fn(res)
    }
  })
}

/**
 * 压缩图片
 * @param {object} img 图片
 * @param {function} fn 回调函数
 */
function compressImg (img, fn) {
  const selectorQuery = uni.createSelectorQuery()
  selectorQuery.select(\'#canvas\')
    .fields({node: true, size: true})
    .exec(res => {
      const canvas = res[0].node
      const ctx = canvas.getContext(\'2d\')
      canvas.height = img.height
      canvas.width = img.width

      let seal = canvas.createImage();
      seal.src = img.path;
      seal.onload = () => {
        ctx.drawImage(seal, 0, 0, img.width, img.height)
        const url = canvas.toDataURL(\'image/jpeg\', .1)
        fn(url)
      }
    })
}

使用方法

getImageObject(list[0].file.path, img => {
  compressImg(img, res => {
    console.log(res);
  })
})

新发现

base64字符的长度就是文件尺寸