Home > Web Front-end > JS Tutorial > How to Convert a Data URL Back to a Blob Instance in JavaScript?

How to Convert a Data URL Back to a Blob Instance in JavaScript?

Barbara Streisand
Release: 2024-10-26 09:59:29
Original
919 people have browsed it

How to Convert a Data URL Back to a Blob Instance in JavaScript?

Retrieving Blob Instance from DataURL

Converting arbitrary data into a Data URL using FileReader's readAsDataURL() is a common task. However, when the need arises to revert a Data URL back into a Blob instance, the built-in browser APIs may seem unclear.

Resolving this issue, Matt has offered a solution in a previous discussion (How to convert dataURL to file object in javascript?). While BlobBuilder is now deprecated, the updated code effectively converts Data URLs into Blobs:

<code class="js">function dataURItoBlob(dataURI) {
  const byteString = atob(dataURI.split(',')[1]);
  const mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

  const ab = new ArrayBuffer(byteString.length);
  const ia = new Uint8Array(ab);

  for (let i = 0; i < byteString.length; i++) {
    ia[i] = byteString.charCodeAt(i);
  }

  return new Blob([ab], { type: mimeString });
}</code>
Copy after login

This code snippet effortlessly transforms Data URLs into Blobs, addressing the initial query and offering a practical tool for data manipulation.

The above is the detailed content of How to Convert a Data URL Back to a Blob Instance in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template