欧美三级国产三级日韩三级_亚洲熟妇丰满大屁股熟妇_欧美亚洲成人一区二区三区_国产精品久久久久久模特

uniapp 開(kāi)發(fā)小程序壓縮圖片 - 新聞資訊 - 云南小程序開(kāi)發(fā)|云南軟件開(kāi)發(fā)|云南網(wǎng)站建設(shè)-昆明葵宇信息科技有限公司

159-8711-8523

云南網(wǎng)建設(shè)/小程序開(kāi)發(fā)/軟件開(kāi)發(fā)

知識(shí)

不管是網(wǎng)站,軟件還是小程序,都要直接或間接能為您產(chǎn)生價(jià)值,我們?cè)谧非笃湟曈X(jué)表現(xiàn)的同時(shí),更側(cè)重于功能的便捷,營(yíng)銷的便利,運(yùn)營(yíng)的高效,讓網(wǎng)站成為營(yíng)銷工具,讓軟件能切實(shí)提升企業(yè)內(nèi)部管理水平和效率。優(yōu)秀的程序?yàn)楹笃谏?jí)提供便捷的支持!

您當(dāng)前位置>首頁(yè) » 新聞資訊 » 小程序相關(guān) >

uniapp 開(kāi)發(fā)小程序壓縮圖片

發(fā)表時(shí)間:2021-2-3

發(fā)布人:葵宇科技

瀏覽次數(shù):151

小程序壓縮圖片和普通 html 壓縮圖片思路一致。

步驟為:

  1. 獲取圖片信息
  2. 獲取canvas 節(jié)點(diǎn)
  3. 創(chuàng)建圖片對(duì)象
  4. 壓縮圖片

詳細(xì)代碼

/**
 * 獲取圖片信息
 * @param {string} imgObj 圖片對(duì)象path
 * @param {function} fn 回調(diào)函數(shù)
 * @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 回調(diào)函數(shù)
 */
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 = http://www.wxapp-union.com/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);
  })
})

新發(fā)現(xiàn)

base64字符的長(zhǎng)度就是文件尺寸 

/**
 * 返回圖片尺寸
 * @param {string} url base64 url
 * @param {functino} fn 返回圖片尺寸
 */
function getSize(url, fn) {
  let arr = url.split(',')[1],
    bstr = atob(arr),
    n = bstr.length;
  fn(n)
}

普通壓縮圖片處理

這里假設(shè)壓縮上傳的文件。

步驟為:

  1. 獲取 File 文件
  2. File && filereader.readAsDataURL(file) 生成 base64 編碼
  3. 創(chuàng)建 Image 對(duì)象 && Image.src = http://www.wxapp-union.com/base64 url
  4. 創(chuàng)建 canvas && ctx.drawImage() && canvas.toDataURL(type, encoderOptions)
  5. 生成 base64 url

詳細(xì)代碼

  function Compress(obj) {
    this.file = obj.file
    this.fileType = this.file.type // mime type
    this.filename = this.file.name // 文件名
    this.beforeSize = this.file.size
    this.factor = obj.factor // 壓縮比例(取值范圍:0-1)
  }

  /**
  * 生成 base64 url
  * @params { File } file 文件
  * @params { function } fn 回調(diào)函數(shù)
  * */
  function toDataurl(file, fn) {
    const filereader = new FileReader()
    filereader.readAsDataURL(file)
    
    filereader.onload = () => {
      const url = filereader.result
      if (url) {
        // ---------vvvvvvvv 測(cè)試句 vvvvvvvv---------
        addImg(url)
        // ---------^^^^^^^ 測(cè)試句 ^^^^^^^----------
        fn(url)
        console.info('before: ' + file.size)
      } else {
        console.error('filereader error');
      }
    }
  }

  /**
  * 創(chuàng)建 image 對(duì)象
  * @params { string } base64 url
  * @params { string } filename 文件名
  * @params { function } fn 回調(diào)函數(shù)
  * */
  function dataurl2File (url, filename, fn) {
    let type = url.split(',')[0].replace(/^.*:(.*);.*$/, '$1'), 
          arr = url.split(',')[1], 
          bstr = atob(arr), 
          n = bstr.length;
    let u8arr = new Uint8Array(n); 
  
    while(n --) {
      u8arr[n] = bstr.charCodeAt(n)
    }

    const file = new File([u8arr], filename, {type: type})
    fn(file)
  }

  /**
  * 創(chuàng)建 image 對(duì)象
  * @params { string } base64 編碼
  * @params { function } fn 回調(diào)函數(shù)
  * */
  function createImg(dataurl, fn) {
    const img = new Image()
    img.src = http://www.wxapp-union.com/dataurl
    img.onload = () => {
      fn(img)
    }
  }

  Compress.prototype = {
    /**
    * 文件生成 base64 url => 創(chuàng)建 image 對(duì)象
    * */
    init() {
      toDataurl(this.file, url => {
        createImg(url, img => {
          this.run(img)
        })
      })
    },
    /**
    * 創(chuàng)建 canvas 對(duì)象 => 壓縮并轉(zhuǎn)化為圖片
    * */
    run(img) {
      const canvas = document.createElement('canvas')
      const ctx = canvas.getContext('2d')
      canvas.width = img.width
      canvas.height = img.height
      ctx.drawImage(img, 0, 0, canvas.width, canvas.height)

      // 此句為實(shí)現(xiàn)壓縮關(guān)鍵句
      this.newDataurl = canvas.toDataURL('image/jpeg', this.factor)
      // ---------vvvvvvvv 測(cè)試句 vvvvvvvv---------
      addImg(this.newDataurl)
      // ---------^^^^^^^ 測(cè)試句 ^^^^^^^----------

      dataurl2File(this.newDataurl, this.filename, (file) => {
        console.info('after: ' + file.size);

        if (this.beforeSize > file.size) {
          console.info('壓縮成功');
        } else {
          console.error('壓縮失敗');
        }
      })
    }
  }
  /**
  * 對(duì)比壓縮前后的兩個(gè)圖片
  * */
  function addImg (url) {
    const img = new Image()
    img.src = http://www.wxapp-union.com/url

    document.body.appendChild(img)
  }

使用方法

  /**
  * 獲取上傳文件,創(chuàng)建壓縮圖片實(shí)例,壓縮圖片
  * */
  function compressFile() {
    const dom = document.querySelector('[name=file]')

    dom.addEventListener('change', () => {
      const file = dom.files[0]
      const cp = new Compress({
        file: file,
        factor: 0.1
      })
      cp.init()
    })
  }

  window.onload = function () {
    compressFile()
  }

報(bào)錯(cuò)處理

1、 小程序 canvas drawImage 報(bào)錯(cuò):

TypeError: Failed to execute 'drawImage' 報(bào)錯(cuò)
解決辦法

let seal = canvas.createImage();
seal.src = http://www.wxapp-union.com/img.path;
seal.onload = () => {
  ctx.drawImage(seal, 0, 0, img.width, img.height)
  // 壓縮圖片
  const url = canvas.toDataURL('image/jpeg', .1)
}

??:壓縮圖片時(shí)要注意 canvas.toDataURL 的第一個(gè)參數(shù)是 image/jpeg 或 image/webp 時(shí)可以壓縮。

相關(guān)案例查看更多