js converts the image blob object and the image base64 to each other

  1. Copy and encapsulate the following code in the xxx.js file, and place it under the project folder utils

    /**
     * 图片blob转图片base64
     * @param blob 
     */
    export function blobToBase64 (blob) {
          
          
    	return new Promise((resolve, reject) => {
          
          
    		const fileReader = new FileReader()
    		fileReader.onload = (e) => {
          
          
    			resolve(e.target.result)
    		}
    		// readAsDataURL
    		fileReader.readAsDataURL(blob)
    		fileReader.onerror = () => {
          
          
    			reject(new Error('blobToBase64 error'))
    		}
    	})
    }
    
    /**
     * 图片base64转blob
     * @param base64 base64图片
     */
    export function base64ToBlob (base64) {
          
          
    	let bstr = window.atob(base64),
    		n = bstr.length,
    		u8arr = new Uint8Array(n);
    	while (n--) {
          
          
    		u8arr[n] = bstr.charCodeAt(n)
    	}
    	return new Blob([u8arr], {
          
           type: base64})
    }
    
  2. Use: import xxx.js file, call method

    // 注意引入路径不要出错
    import {
          
           blobToBase64, base64ToBlob } from '@/utils/xxx.js'
    
    blobToBase64(blob).then(res => {
          
          
    	// 输出图片base64
    	console.log(res)
    }).catch(err => {
          
          
    	console.log(err)
    })
    
    let blob = base64ToBlob(base64)
    // 输出图片bolb对象
    console.log(blob)
    

Guess you like

Origin blog.csdn.net/lhh_gxx/article/details/128377259