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

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

DDD
Release: 2024-10-29 21:20:30
Original
591 people have browsed it

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

Converting Data URLs to Blobs

Transforming arbitrary data into a Data URL using FileReader's readAsDataURL() is a useful technique. However, what if you need to convert that Data URL back into a Blob instance?

Browser-Native Conversion

Currently, there is no built-in browser API that directly converts Data URLs to Blobs. However, there are workaround solutions that utilize custom JavaScript code.

Custom JavaScript Solution

A widely accepted method was proposed by Matt on Stack Overflow (How to convert dataURL to file object in javascript?). Here's an updated version of his code:

<code class="javascript">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);
  }

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

Usage

You can now use dataURItoBlob() to transform your Data URL into a Blob object:

<code class="javascript">const dataURL = 'data:image/png;base64,...';
const blob = dataURItoBlob(dataURL);</code>
Copy after login

The above is the detailed content of How to Convert a Data URL to a Blob 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
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!