Home  >  Article  >  Web Front-end  >  Can you convert a Data URL back into a Blob using JavaScript?

Can you convert a Data URL back into a Blob using JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-26 03:14:02933browse

 Can you convert a Data URL back into a Blob using JavaScript?

Retrieving Blobs from DataURLs

Question:

Using FileReader's readAsDataURL() method, one can convert data into a Data URL. However, is there a method to reverse this process and create a Blob instance from the Data URL using built-in browser APIs?

Answer:

A solution was proposed by Matt a year ago in the discussion thread "How to convert dataURL to file object in javascript?"

Updated Code:

Since BlobBuilder has been deprecated, here's the updated code:

<code class="javascript">function dataURItoBlob(dataURI) {
  // Convert base64 to raw binary data as a string
  let byteString = atob(dataURI.split(',')[1]);

  // Extract the MIME type
  let mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

  // Convert the string to an ArrayBuffer
  let ab = new ArrayBuffer(byteString.length);
  let ia = new Uint8Array(ab);

  // Set the ArrayBuffer bytes to the appropriate values
  for (let i = 0; i < byteString.length; i++) {
    ia[i] = byteString.charCodeAt(i);
  }

  // Create a Blob from the ArrayBuffer
  let blob = new Blob([ab], { type: mimeString });
  return blob;
}</code>

The above is the detailed content of Can you convert a Data URL back into a Blob using 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