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

Can You Convert a Data URL Back to a Blob in JavaScript Using Built-in APIs?

Linda Hamilton
Release: 2024-10-26 08:22:30
Original
518 people have browsed it

 Can You Convert a Data URL Back to a Blob in JavaScript Using Built-in APIs?

Obtaining a Blob from a DataURL

In certain scenarios, there is a need to transform arbitrary data into a Data URL using FileReader's readAsDataURL() method. However, can this Data URL be converted back into a Blob instance utilizing built-in browser APIs?

A solution has been proposed by a user named Matt:

Code Snippet:

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

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

  // Create an ArrayBuffer and Uint8Array
  var ab = new ArrayBuffer(byteString.length);
  var ia = new Uint8Array(ab);

  // Set the bytes of the buffer
  for (var i = 0; i < byteString.length; i++) {
    ia[i] = byteString.charCodeAt(i);
  }

  // Create a Blob instance
  var blob = new Blob([ab], { type: mimeString });
  return blob;
}</code>
Copy after login

Note:

As mentioned in subsequent comments, BlobBuilder has become deprecated. Therefore, the code provided above is an updated version.

The above is the detailed content of Can You Convert a Data URL Back to a Blob in JavaScript Using Built-in APIs?. 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!