Take a look at this picture first

This is from a gold digger’s… I forgot what it was called. Thank you!

Anyway, let’s start with MDN and see what’s in this diagram.

Based on the API

blob

Blob represents an immutable, raw data-like file object. It can be read as binary or text. It can also be converted to stream files.

Create a BLOb data using blob().


/ * * * *@array {bolb, ArrayBuffer DOMstring... }
 * @options The MIME type of the array content. * /
var blob = new Blob(array,options);

Copy the code

Instance properties


  • size
  • type

Method of instance


  • blob.arrayBuffer()
    • Returns a Promise object containing the binary data of an arrayBuffer.
         / / use
         let bufferPromise  = blob.arrayBuffer();
         let buffer = await blob.arrayBuffer();
      Copy the code
  • blob.slice()
    • Blobs can be cut into small bloBs. It’s like an array.
          let Ablob = blob.splice(0.2.' ')
          // Return the clipped part
      Copy the code
  • blob.stream()
    • The ReadableStream () method returns a ReadableStream object that, when read, returns the data contained in the Blob.
      let ReadableStream = blob.stream();
    Copy the code
  • blob.text()
    • Method returns a Promise object containing the contents of the BLOB, encoded in UTF-8 format.
          var textPromise = blob.text();
          var text = await blob.text();
      Copy the code

file

File is an inheritance from blob.

File reads file information.

  [file].type
  [file].size
  [file].name
Copy the code

The file file is the fileList selected by the user through the input.

Or drag the generated XX object (I just drag upload is this API), this will be learned later.

File handles the same as blob.

Files and blobs can be processed using FileReader and url.createObjecturl () and xmlHttprequest.send ().

Inherited methods

  file.splice(start,end,' ')
Copy the code

FileReader

File objects allow Web applications to asynchronously read the contents of the raw data buffer, using file and BLOb objects to specify files or data to read.

Read blob, file, etc

  let reader = new FileReader()
  reader.onload = (e) = >{
    console.log(e.target.result)
  }
  reader.readAsDataURL( new Blob() )
Copy the code

The above code demonstrates creating a FileReader. Read the specified content via readAsDataURL, and return the content of Base64 in target.result in onLoad (after reading).

In addition, it has several methods.

Read.readastext () returns string content in result. ReadAsArrayBuffer () returns string content in resultArrayBufferThe data object reader. ReadAsBinaryString () returns the binary data in the resultCopy the code

URL.createObjectURL

This method comes from the URL

It allows the browser to specify a file or blob and convert it to a DOMString. He and DOM is closely linked, so we are not in use after he has finished the DOMString transformation, we need to use Windows. URL. RevokeObjectURL (URL) to release it, get the best performance results.

The base application

File download

Link type file download we divided into the following steps

  • The resource file is converted to bloB type
    • When we download a resource link for a file, we can use Ajax for the resource of the fileresponseTypeSet toblob.

    This gives us a bloB file. This file is stored in the browser buffer.

  • Obtain the file address of the buffer, with a label to achieve download.
    • The browser provides the url.createObjecturl () method, which converts the link address into a front-end URL link for the blob. A Tag Download

    The downloading process of tag A is not within the scope of this study.

  • Once the download has been implemented we need to release the files in this buffer.
    • window.URL.revokeObjectURL(url)

See the following code:

<DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title> <script SRC =".. /ajax/index.js"></script> </head> <body> <div onclick="downloadFiel()"> </div> <script> let fileUrl = 'https://bloggers-1304641141.cos.ap-beijing.myqcloud.com/img/1636095726424.jpg'; const downloadFiel = function (url){ ajax({ type:"get", reqireUrl: url || fileUrl, responseType:"blob", success:function (res){ let a = document.createElement('a'); // Convert the bloB image returned by Ajax to a BLOB-type URL (DOMString); let url = window.URL.createObjectURL(res) a.href = url; // Clipping the last type edit, Edit download name a.townLoad = 'test.'+ Fileurl.split ('.').reverse()[0] // trigger a tag a.lick () // release blob DOMString window.URL.revokeObjectURL(url) } }) } </script> </body> </html>Copy the code

Canvas image processing.

Canvas image processing idea

1. Here we select the file and render it with url.createObjecturl () to a BLOB URL.

2. We can load the Image with new Image() and process the Image using canvas.

3. Finally use Canvas.toblob () to convert the processed image into a BLOb file.

4. Use url.createObjecturl () to download the blob URL and save it.

The process

Well, the logic is relatively simple, and then directly write the entire code, can be assigned to the following code directly look at. It’s a little rough. You can optimize the following, (● strap strap ●).


<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Canvas image processing</title>
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <style>
        .img {
            margin-top: 15px;
            text-align: center;
        }
        .btn{
            display: inline-block;
            width: 100px;
            height: 35px;
            line-height: 35px;
            background-color: #42b983;
            border-radius: 20px;
            text-align: center;
            color: #fff;
            transition: 0.4 s;
        }
        .btn:hover{
            cursor: pointer;
            opacity: 0.8;
            transition: 0.4 s;
        }
    </style>
</head>
<body>
<div class="img">
    <canvas id="image"></canvas>
</div>
<div class="file">
    <input accept="image/*" id="file" type="file"> <div class="btn" id="save">Bao deposit</div>
</div>
<script>

  window.URL =  window.URL || window.webkitURL ;

  let file = document.getElementById('file');
  let canvas = document.getElementById('image');
  let btn = document.getElementById('save')
  let ctx = canvas.getContext('2d');
  canvas.width = 270;
  canvas.height = 270;
  let img = new Image();

  // Define the flag star array
  let stars = []

  file.onchange = function (e) {
    // Use createObjectURL to find the address character pass in the corresponding cache
    let url = window.URL.createObjectURL(e.target.files[0])
    img.onload = function () {
      handleDraw();
    }
    img.src = url;
  }

  btn.onclick = function (){
    if(file.files.length<1){
      alert('Please select picture')
      return
    }
    canvas.toBlob(function (e){
      let saveUrl = window.URL.createObjectURL(e)
      let a = document.createElement('a')
      console.log(saveUrl)
      a.href=saveUrl
      a.download = 'save.png'
      console.log(a)
      a.click()
      window.URL.revokeObjectURL(saveUrl)
    })
  }

  // Use CRC to set rounded corners
  const handleBorderRect = (ctx, x, y, w, h, r, color) = > {
    ctx.beginPath();
    / / the top left corner
    ctx.arc(x + r, y + r, r, Math.PI, 1.5 * Math.PI);
    ctx.moveTo(x + r, y);
    ctx.lineTo(x + w - r, y);
    ctx.lineTo(x + w, y + r);
    / / the top right corner
    ctx.arc(x + w - r, y + r, r, 1.5 * Math.PI, 2 * Math.PI);
    ctx.lineTo(x + w, y + h - r);
    ctx.lineTo(x + w - r, y + h);
    / / the bottom right hand corner
    ctx.arc(x + w - r, y + h - r, r, 0.0.5 * Math.PI);
    ctx.lineTo(x + r, y + h);
    ctx.lineTo(x, y + h - r);
    / / the bottom left corner
    ctx.arc(x + r, y + h - r, r, 0.5 * Math.PI, Math.PI);
    ctx.lineTo(x, y + r);
    ctx.lineTo(x + r, y);

    ctx.fillStyle = color;
    ctx.fill();
    ctx.closePath();
  };


  class Star {
    constructor(ctx, x, y, size) {
      this.ctx = ctx
      this.ponits = []
      this.color = 'yellow'
      for (let i = 1; i <= 5; i++) {
        let temp = {
          x: Math.cos((18 + i * 72) / 180 * Math.PI) * size + size + x,
          y: -Math.sin((18 + i * 72) / 180 * Math.PI) * size + size + y,
          sx: Math.cos((54 + i * 72) / 180 * Math.PI) * 0.4 * size + size + x,
          sy: -Math.sin((54 + i * 72) / 180 * Math.PI) * 0.4 * size + size + y,
        }
        this.ponits.push(temp);
      }
      stars.push(this)}draw() {
      let list = this.ponits
      this.ctx.beginPath()
      for (let i = 0; i < list.length; i++) {
        let temp = list[i]
        ctx.lineTo(temp.x, temp.y)
        ctx.lineTo(temp.sx, temp.sy)
      }
      this.ctx.fillStyle = this.color
      this.ctx.fill()
      this.ctx.closePath()
    }
  }

  // Add pentagram
  const drawStart = (ctx) = > {
    // Compute the coordinates of the points on the circle
    function getXyByRound(h, r) {
      return {
        y: Math.sin(Math.PI * 2 / 360 * h) * r,
        x: Math.cos(Math.PI * 2 / 360 * h) * r
      }
    }
    new Star(ctx, 20.40.25)
    let index = 0
    while (index < 4) {
      let temp = getXyByRound(index*27.60)
      index++
      new Star(ctx, temp.x+20, temp.y+40.10)
    }

    stars.forEach(star= > star.draw())
  }

  // Add a gradient mask
  const drawReact = (ctx, x, y, w, h) = > {
    let gradient = ctx.createLinearGradient(x, y, w, h)
    ctx.beginPath()
    gradient.addColorStop(0.'rgba(255,0,0,.9)')
    gradient.addColorStop(1.'rgba (255,0,0,0)')
    ctx.fillStyle = gradient
    ctx.fillRect(0.0, w, h)
    ctx.closePath();
  }

  const handleDraw = () = > {
    // Trim rounded corners
    handleBorderRect(ctx, 10.10.250.250.14.'orange');
    ctx.clip();
    // Draw a picture
    ctx.drawImage(img, 10.10.250.250);
    // Add gradient
    drawReact(ctx, 10.10.270.270);
    // Add pentacle column
    drawStart(ctx);
  };


</script>
</body>
</html>


Copy the code

Test/exclude

After testing, it is not feasible to download pictures in the wechat browser of mobile phone, but it is possible in the built-in browser of mobile phone.

Therefore, when there is a need to download pictures in wechat,

You can boot to an external browser, or wrap the image with the A tag, open the image and press long to download.