Front-end with compressed js upload pictures

Kernel

/**
 * 压缩图片
 * @param fileObj 传入的文件对象
 * @returns {Promise} resolved promise 返回压缩后的新图片blob对象,可以直接用于表单提交
 * @example 当前页面显示blob对象图片实例
 *  let file = document.getElementById('input_file').files[0]
 compressImage(file).then(result=>{
        console.log(result)
        let img_src = URL.createObjectURL(result)
        document.getElementById('img').src=img_src
    })
 */
function compressImage (fileObj) {
  const WIDTH = 1200  // 压缩后的图片宽度(高度自适应)
  const QUALITY = 0.6 // 压缩后的质量(0-1),数值越小,压缩后的图片文件越小,画质越低

  return new Promise((resolve, reject) => {
    let reader = new FileReader()
    reader.readAsDataURL(fileObj)
    reader.onload = function (e) {
      let image = new Image() // 在内存中新建一个img标签,用来绘制压缩后的图片
      image.src = e.target.result
      image.onload = function () {
        let canvas = document.createElement('canvas'),
          context = canvas.getContext('2d'),
          ratio = image.height / image.width // 计算宽高比

        canvas.width = WIDTH
        canvas.height = WIDTH * ratio

        context.drawImage(image, 0, 0, canvas.width, canvas.height)

        canvas.toBlob(blob => {
          resolve(blob)
        }, 'image/jpeg', QUALITY)
      }
    }
  })
}

The demo page

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>压缩图片demo</title>
</head>

<body>
    <img id="img" src="">
    <input type="file" onchange="test(this.files[0])">
</body>
<script>

    function compressImage(fileObj) {
        const WIDTH = 1200  // 压缩后的图片宽度(高度自适应)
        const QUALITY = 0.6 // 压缩后的质量(0-1),数值越小,压缩后的图片文件越小,画质越低

        return new Promise((resolve, reject) => {
            let reader = new FileReader()
            reader.readAsDataURL(fileObj)
            reader.onload = function (e) {
                let image = new Image() // 在内存中新建一个img标签,用来绘制压缩后的图片
                image.src = e.target.result
                image.onload = function () {
                    let canvas = document.createElement('canvas'),
                        context = canvas.getContext('2d'),
                        ratio = image.height / image.width // 计算宽高比

                    canvas.width = WIDTH
                    canvas.height = WIDTH * ratio

                    context.drawImage(image, 0, 0, canvas.width, canvas.height)

                    canvas.toBlob(blob => {
                        resolve(blob)
                    }, 'image/jpeg', QUALITY)
                }
            }
        })
    }

    function test(file) {
        compressImage(file).then(result => {
            console.log(result)
            let img_src = URL.createObjectURL(result)
            document.getElementById('img').src = img_src
        })
    }
</script>

</html>
Published 219 original articles · won praise 99 · views 490 000 +

Guess you like

Origin blog.csdn.net/lpwmm/article/details/105253021