Home > Web Front-end > JS Tutorial > body text

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

Mary-Kate Olsen
Release: 2024-10-26 03:14:02
Original
880 people have browsed it

 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>
Copy after login

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!