Creating a BLOB from a Base64 string in JavaScript

后端 未结 12 2632
说谎
说谎 2020-11-21 04:24

I have Base64-encoded binary data in a string:

const contentType = \'image/png\';
const b64Data = \'iVBORw0KGg         


        
12条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-21 04:48

    Following is my TypeScript code which can be converted easily into JavaScript and you can use

    /**
     * Convert BASE64 to BLOB
     * @param base64Image Pass Base64 image data to convert into the BLOB
     */
    private convertBase64ToBlob(base64Image: string) {
      // Split into two parts
      const parts = base64Image.split(';base64,');
    
      // Hold the content type
      const imageType = parts[0].split(':')[1];
    
      // Decode Base64 string
      const decodedData = window.atob(parts[1]);
    
      // Create UNIT8ARRAY of size same as row data length
      const uInt8Array = new Uint8Array(decodedData.length);
    
      // Insert all character code into uInt8Array
      for (let i = 0; i < decodedData.length; ++i) {
        uInt8Array[i] = decodedData.charCodeAt(i);
      }
    
      // Return BLOB image after conversion
      return new Blob([uInt8Array], { type: imageType });
    }
    

提交回复
热议问题