This article was originally published at: github.com/bigo-fronte… Welcome to follow and reprint.

preface

The js file type should be converted several times.

What are Blob, File, DataURL

Blob

The Blob type is a parent of the File type and represents an immutable, raw data-like File object. How do I get a BLOB object?

new Blob(array, options)
let hiBlob = new Blob([`

Hi gauseen!

`

] and {type: 'text/html' }) Copy the code

In the code above, we create a BLOb object and declare the text/ HTML type, just like we create an.html file. It’s just in the browser’s memory.

The File type

File contains information about a File, whose contents can be accessed through JS

How do I get a File object?

1.new File(bits, name[, options])

// 1. Arguments are arrays of strings
let hiFile = new File([`

Hi gauseen!

`

].'fileName', { type: 'text/html' }) // 2. Change blob to file let hiBlob = new Blob([`

Hi gauseen!

`

] and {type: 'text/html' }) let hiFile = new File([ hiBlob ], 'fileName', { type: 'text/html' }) Copy the code

Using the File constructor, create a File object similar to the blob mentioned above. Blobs can be cast to type file, which means that bloBs retrieved above can be cast to type file.

2.inputElement.files

Get the File object from the label

// input The change event is triggered when a file is uploaded
$('input').addEventListener('change'.e= > {
  let file = e.target.files[0]
  console.log('file: ', file)
})
Copy the code

3.DragEvent.dataTransfer.files

Get the File object by dragging and dropping

DataURL (base64)

DataURL, prefixed with data: protocol URL, can store small data

Grammar: data: [] [; base64]

Here is a black 1 pixel example:

data:image/gif; base64,R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs=

The Blob File types mentioned above, how do you “consume” them? And then look down

1.FileReader

Allows Web applications to asynchronously read files (BLObs or files) stored on the user’s computer.

// Convert blob or file to DataURL (base64) form
fileReader(someFile).then(base64= > {
  console.log('base64: ', base64)
})

function fileReader (blob) {
  return new Promise((resolve, reject) = > {
    let reader = new FileReader()
    reader.onload = (e) = > {
      resolve(e.target.result)
    }
    reader.readAsDataURL(blob)
  })
}
Copy the code

2.convasElement.toDataURL()

Images can be converted to dataURL form through canvas image processing capability. The code was implemented in the Blob section above.

DataURL, File and Blob transfer

DataURL to Blob object

DataURL to Blob object
export function dataURLToBlob(dataurl, mine = 'image/jpeg') :Blob {
  const arr = dataurl.split(",");
  const mimeType = mine || arr[0].match(/ : (. *?) ; /) [1];
  const bstr = atob(arr[1]);
  let n = bstr.length;
  const u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], { type: mimeType });
}
Copy the code

DataURL to File object

DataURL to File object
function dataURLtoFile(dataurl, filename, mine = 'image/jpeg') {
  const arr = dataurl.split(', ');
  const mimeType = mine || arr[0].match(/ : (. *?) ; /) [1];
  const bstr = atob(arr[1])
  let n = bstr.length;
  const u8arr = new Uint8Array(n);
  while(n--){
      u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], filename, {type:mimeType});
}
Copy the code

More transformation way: blog.csdn.net/hahahhahaha…

GIF capture plugin SuperGif

Principle: Image identifier (Image Descriptor)

A GIF file can contain more image, an image is done then identifier is an image, image identifier with 0 x2c (‘, ‘) character, defined and then it’s the nature of the image, including image offset relative to the logical screen borders, and the size of the image, and presence of local color size list and color list, Consists of 10 bytes

Open source plugin: github.com/buzzfeed/li…

Iv. Antd Upload component processing

The project framework uses ANTD, so the first frame capture is required when the call is sent back. The upload component callback parameter returns the File type

  1. File is converted to dataUrl
  2. Create an IMG instance to receive dataUrl data
  3. Initialize the SuperGif instance
  4. Capture the first frame image and return the dataUrl data
  5. DataUrl is converted to file data
  6. Upload the image to the service interface
export function getGIFFirstFrame(file) :Promise<File> {
  return new Promise((resolve) = > {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () = > {
      const img = new Image();
      // @ts-ignore
      img.src = reader.result;
      img.onload = () = > {
        // @ts-ignore
        const rub = new SuperGif({ gif: img });
        rub.load(function () {
          if (rub.get_length() === 0) {
            return;
          }
          // Get the first frame of the GIF instance
          rub.move_to(0);
          // Canvas generates base64 image data
          const dataurl = rub.get_canvas().toDataURL("image/jpeg".0.8);
          const filename = file.name.replace('.gif'.'.jpg');
          resolve(dataURLtoFile(dataurl, filename));
          return;
        });
      };
    };
  });
  
}
Copy the code

Welcome everyone to leave a message to discuss, wish smooth work, happy life!

I’m bigO front. See you next time.