Home  >  Article  >  Web Front-end  >  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
Barbara StreisandOriginal
2024-10-26 09:59:29847browse

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>

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!

Statement:
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