The front-end compresses the picture to the specified width and height

Principle of compressing pictures

  1. Get the image file to be uploaded through the native input tag
  2. Convert image files into img element tags
  3. Compress and draw the HTMLImageElement on the canvas
  4. Convert the image into a data URI containing the image display, that is, the image is converted into a base64-encoded string

accomplish

Get the uploaded image file through the native input tag

  1. css part
    <input
      ref="image"
      type="file"
      accept="image/*"
      @change="getFile"
    />
    
  2. After the image is uploaded, the uploaded image file can be obtained through the following code, here is an array of FileList file objects, as shown in the figure below. Because we are uploading a single file here, the first file object in the array is directly taken as the image file we uploaded
    this.$refs.image.files[0]
    
    insert image description here

Convert image files into img element tags

  1. Since the file obtained through input is a file object type, it needs to be converted into an img object before compression, and the following method can be used

    fileToImg (file) {
          
          
      return new Promise((resolve, reject) => {
          
          
        const img = new Image()
        const reader = new FileReader()
        reader.onload = function (e) {
          
          
          img.src = e.target.result
        }
        reader.onerror = function (e) {
          
          
          reject(e)
        }
        reader.readAsDataURL(file)
        img.onload = function () {
          
          
          resolve(img)
        }
        img.onerror = function (e) {
          
          
          reject(e)
        }
      })
    }
    

Compress and draw the HTMLImageElement on the canvas, and convert the image into a base64 encoded string

  1. After converting the picture into an img object, you can create a canvas object, and compress and draw a picture with a suitable width and height on the canvas. There are two cases here:

    1. Compress the image to a specified height
    /**
     * 压缩图片
     * @param img 被压缩的img对象
     * @param height 触发压缩的图片固定高度
     */
    compressImgHeight (img, height) {
          
          
      return new Promise((resolve) => {
          
          
      	// 创建canvas对象
        const canvas = document.createElement('canvas')
    
        const context = canvas.getContext('2d')
    	// 获取上传的img图片对象的宽度和高度
        const {
          
           width: originWidth, height: originHeight } = img
    
        // 绘制图片的高度
        canvas.height = height
    	// 根据绘制图片的高度,等比例计算图片的宽度
        canvas.width = (originWidth * canvas.height) / originHeight
    
        // 将img绘制到画布上
        context.drawImage(img, 0, 0, canvas.width, canvas.height)
    
        // 转为一个包含图片展示的data URI,即图片被转换成base64编码的字符串,格式为jpeg
        // 0.8为图片质量,区间为0~1,默认0.92
        resolve(canvas.toDataURL('image/jpeg', 0.8))
      })
    },
    
    1. Compress the image to the specified width
    /**
     * 压缩图片
     * @param img 被压缩的img对象
     * @param width 触发压缩的图片固定宽度
     */
    compressImgHeight (img, width) {
          
          
      return new Promise((resolve) => {
          
          
      	// 创建canvas对象
        const canvas = document.createElement('canvas')
    
        const context = canvas.getContext('2d')
    	// 获取上传的img图片对象的宽度和高度
        const {
          
           width: originWidth, height: originHeight } = img
    
        // 绘制图片的宽度
        canvas.width = width
    	// 根据绘制图片的宽度,等比例计算图片的高度
        canvas.height = (originHeight * canvas.width) / originWidth
    
        // 将img绘制到画布上
        context.drawImage(img, 0, 0, canvas.width, canvas.height)
    
        // 转为一个包含图片展示的data URI,即图片被转换成base64编码的字符串,格式为jpeg
        // 0.8为图片质量,区间为0~1,默认0.92
        resolve(canvas.toDataURL('image/jpeg', 0.8))
      })
    }
    

Summarize

  1. Summarize the above code
    // css部分
    <input
      ref="image"
      type="file"
      accept="image/*"
      @change="getFile"
    />
    
    
    // js部分
    getFile () {
          
          
      this.readImg(this.$refs.image.files[0]).then(res => {
          
          
      	// 压缩图片为指定宽度
        this.compressImgHeight(res, 300).then(img => {
          
          
          // 输出压缩后的图片base64
          console.log(img)
        })
      })
    }
    
    /**
     * 将图片file对象转化为img对象
     * @param file 图片file对象
     */
    fileToImg (file) {
          
          
      return new Promise((resolve, reject) => {
          
          
        const img = new Image()
        const reader = new FileReader()
        reader.onload = function (e) {
          
          
          img.src = e.target.result
        }
        reader.onerror = function (e) {
          
          
          reject(e)
        }
        reader.readAsDataURL(file)
        img.onload = function () {
          
          
          resolve(img)
        }
        img.onerror = function (e) {
          
          
          reject(e)
        }
      })
    },
    
    /**
     * 压缩图片为指定宽度
     * @param img 被压缩的img对象
     * @param width 触发压缩的图片固定宽度
     */
    compressImgWidth (img, width) {
          
          
      return new Promise((resolve) => {
          
          
      	// 创建canvas对象
        const canvas = document.createElement('canvas')
    
        const context = canvas.getContext('2d')
    	// 获取上传的img图片对象的宽度和高度
        const {
          
           width: originWidth, height: originHeight } = img
    
        // 绘制图片的宽度
        canvas.width = width
    	// 根据绘制图片的宽度,等比例计算图片的高度
        canvas.height = (originHeight * canvas.width) / originWidth
    
        // 将img绘制到画布上
        context.drawImage(img, 0, 0, canvas.width, canvas.height)
    
        // 转为一个包含图片展示的data URI,即图片被转换成base64编码的字符串,格式为jpeg
        // 0.8为图片质量,区间为0~1,默认0.92
        resolve(canvas.toDataURL('image/jpeg', 0.8))
      })
    },
    
    /**
     * 压缩图片为指定高度
     * @param img 被压缩的img对象
     * @param height 触发压缩的图片固定高度
     */
    compressImgHeight (img, height) {
          
          
      return new Promise((resolve) => {
          
          
      	// 创建canvas对象
        const canvas = document.createElement('canvas')
    
        const context = canvas.getContext('2d')
    	// 获取上传的img图片对象的宽度和高度
        const {
          
           width: originWidth, height: originHeight } = img
    
        // 绘制图片的高度
        canvas.height = height
    	// 根据绘制图片的高度,等比例计算图片的宽度
        canvas.width = (originWidth * canvas.height) / originHeight
    
        // 将img绘制到画布上
        context.drawImage(img, 0, 0, canvas.width, canvas.height)
    
        // 转为一个包含图片展示的data URI,即图片被转换成base64编码的字符串,格式为jpeg
        // 0.8为图片质量,区间为0~1,默认0.92
        resolve(canvas.toDataURL('image/jpeg', 0.8))
      })
    }
    

Guess you like

Origin blog.csdn.net/lhh_gxx/article/details/128704823