js converts image base64 and img objects to each other

  1. Copy and encapsulate the following code in the xxx.js file, and place it under the project folder utils
/**
 * @param {*} base64 图片base64
 */
export function base64ToImg (base64) {
    
    
	return new Promise((resolve, reject) => {
    
    
		const img = new Image()
		img.src = 'data:image/jpeg;base64,' + base64
		img.onload = function () {
    
    
			resolve(img)
		}
		img.onerror = function (e) {
    
    
			reject(e)
		}
	})
}

/**
 * @param {*} image 
 */
export function imgToBase64(image) {
    
    
	var canvas = document.createElement("canvas");
    canvas.width = image.width;
    canvas.height = image.height;
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0, image.width, image.height);
    var dataURL = canvas.toDataURL("image/png");
    return dataURL;
}
  1. Use: import xxx.js file, call method

    // 注意引入路径不要出错
    import {
          
           base64ToImg, imgToBase64 } from '@/utils/xxx.js'
    
    base64ToImg(str).then(res => {
          
          
    	// 输出图片img对象
    	console.log(res)
    }).catch(err => {
          
          
    	console.log(err)
    })
    
    const base64 = imgToBase64(image)
    // 输出图片base64
    console.log(base64)
    

Guess you like

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