In daily development, users will more or less encounter the scene of uploading pictures. With the improvement of photography equipment, more and more large size photos are born. Both storage space and transmission rate have a great impact on the server pressure and user experience.

There are three steps that immediately come to mind to reduce an image from large to small: convert the format, reduce the size, reduce the quality, and in most cases convert the format to better results (PNG to JPEG/webP, for example).

So, how to complete the image compression on the end?

By understanding the API of Canvas, we can know that Canvas can draw pictures, adjust size, clipping area, set picture quality * (only JPG and WebP) *, and most importantly, it can output picture files in specified formats.

Simple implementation

Access to the file

After the image is selected in < Input />, the file information is retrieved, and the image is further read as base64 by FileReader

// ...

inputChanged = (e) = > {
  let that = this
  let file = e.target.files[0]

  // Read the file through FileReader
  let reader = new FileReader()
  reader.readAsDataURL(file)
  // Proceed to the next step after reading
  reader.onload = function (e) {
    / / SRC is base64
    let src = e.target.result
    console.log(src)
    // The next step is to handle SRC
    that.dealImage(src)
  }
}

render() {
  return (
    <div>
      <input onChange={this.inputChanged} type="file" />
    </div>)}Copy the code

Read the pictures

Load the base64 Image from the previous step through the Image object, and then Canvas after onload of the Image

// ...
dealImage = (src) = > {
  let that = this
  let image = new Image()
  image.src = src
  image.onload = function () {
    // Use the Canvas operation to process images
    that.compressImage(image)
  }
}
Copy the code

Canvas processing

// ...

compressImage = (image) = > {
  // Create canvas node
  let canvas = document.createElement('canvas')
  // Get the Canvas action object
  let ctx = canvas.getContext('2d')

  // Read the original image size
  let imageW = image.width, imageH = image.height
  // Specify the size of the output image, proportionally, e.g. limit width is 1024
  let afterW = 1024, afterH = afterW * imageH / imageW

  // Set the canvas canvas size
  canvas.width = imageW
  canvas.height = imageH

  // ----- process
  / / no compression
  // drawImage(image, dx, dy)
  ctx.drawImage(image, 0.0)

  // Compress to the specified size
  // drawImage(image, dx, dy, dWidth, dHeight)
  ctx.drawImage(image, 0.0, afterW, afterH)

  // Capture and compress by position
  // drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)
  ctx.drawImage(image, 20.30.50.60.0.0, afterW, afterH);

  // ----- Displays the result
  PNG by default, jpeg or webP are optional
  // - Get base64 data after processing
  let data = canvas.toDataURL('image/jpeg'.0.8)
  console.log(data)

  // - Convert to BLOB and take the next step in the callback
  canvas.toBlob(function (blob) {
    // Do blob, upload, etc
    console.log(blob)
  }, 'image/webp'.0.8)}Copy the code

drawImage

Canvas-drawimage () = Canvas drawImage()

  • drawImage(image, dx, dy)
  • drawImage(image, dx, dy, dWidth, dHeight)
  • drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)

It is easy to understand what each parameter means by combining the following figure

To get the results

ToDataURL (mimeType, quality) and toBlob(callback, mimeType, quality) can be used to obtain the processing results. When output, mineTpye can be set to convert the format, which is PNG by default. You can also set the quality for JPEG and WebP

Canvas – toDataURL() Canvas – toBlob()

Ready plan

In addition to manual image compression, there are faster and more direct solutions

Compress images before uploading

With compressorjs, you can do a variety of things with an image to reduce its size before uploading, as shown in its Readme documentation.

Download compressed images

Commonly used domestic seven cattle cloud storage picture resources, by understanding the official document seven cattle – picture advanced processing, seven cattle to directly obtain the format conversion, cutting, lower quality, thumbnail, rotation and other operations after the picture.

reference

Canvasapi.cn compressorjs