js converts image url to base64

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

    /**
     * 把url转换为 canvas对象
     * @param url 网络图片地址必须服务器设置允许跨域
     * @returns {Promise<any>}
     */
    export default function urlToCanvas (url) {
          
          
    	return new Promise((resolve) => {
          
          
    		var image = new Image();
    		// 先设置图片跨域属性
    		image.crossOrigin = 'Anonymous';
    		/ 再给image赋值src属性,先后顺序不能颠倒
    		image.src = url;
    		image.onload = function () {
          
          
    			var canvas = document.createElement('CANVAS');
    			// 设置canvas宽高等于图片实际宽高
    			canvas.width = image.width
    			canvas.height = image.height
    			canvas.getContext('2d').drawImage(image, 0, 0)
    			let dataURL = canvas.toDataURL("image/jpeg") // toDataUrl可以接收2个参数,参数一:图片类型,参数二: 图片质量0-1(不传默认为0.92)  			
    			resolve(dataURL)	
        }
        image.onerror = () => {
          
          
          resolve({
          
           message: '相片处理失败' })
        }
      })
    }
    
  2. Use: import xxx.js file, call method

    // 注意引入路径不要出错
    import urlToCanvas from '@/utils/xxx.js'
    
    urlToCanvas(url).then(res => {
          
          
    	// 输出图片base64
    	console.log(res)
    }).catch((err) => {
          
          
    	// 输出图片错误信息
    	console.log(err)
    })
    

  3. insert image description here
    If the following error occurs in the console : Since Canvas cannot operate on cross-domain images, use JS to convert image URLs (such as Baidu images) to base64 in the pure front-end, you must use canvas, so you must enable cross-domain, In addition to enabling cross-origin (image.crossOrigin = 'Anonymous') before executing canvas, the server must also enable cross-origin .

Supongo que te gusta

Origin blog.csdn.net/lhh_gxx/article/details/128377299
Recomendado
Clasificación