1. 程式人生 > 其它 >js圖片壓縮

js圖片壓縮

// 壓縮圖片
/*
config= {
  width: 100, // 壓縮後圖片的寬
  height: 100, // 壓縮後圖片的高
  quality: 1 // 圖片品質(清晰度),取值0-1,
}
*/
export function compressImage(file, config) {
  let files
  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 || this.width let h = config.height || this.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 || 1) // 回撥函式返回file的值(將base64編碼轉成file) files = dataURLtoFile(base64, file['name']) resolve(files) } } }) };
// base64轉碼(將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) } return new File([u8arr], fileName, { type: mime }) }