在 Node.js 中,你可以使用 HTTP 模块来从 URL 读取图片,并将其转换为 base64 编码。下面是一个示例代码:
1 const http = require('http'); 2 const fs = require('fs'); 3 4 const imageUrl = 'http://example.com/image.jpg'; 5 this.getImgBase64(imageUrl) 6 // 获取图片base64 7 async getImgBase64(url) { 8 let base64Img 9 return new Promise(function (resolve, reject) { 10 let req = http.get(url, function (res) { 11 let chunks = []; 12 let size = 0; 13 res.on("data", function (chunk) { 14 chunks.push(chunk); 15 size += chunk.length; //累加缓冲数据的长度 16 }); 17 res.on("end", function (err) { 18 //Buffer.concat()方法将chunks中的所有缓冲区对象合并为一个缓冲区对象 19 let data = Buffer.concat(chunks, size); 20 base64Img = data.toString("base64"); 21 resolve({ success: true, base64Img }); 22 }); 23 }); 24 req.on('error', (e) => { 25 resolve({ success: false, errmsg: e.message }); 26 }); 27 req.end(); 28 }) 29 }
标签:node,function,http,url,base64,let,chunks From: https://www.cnblogs.com/Jeanchjy/p/18082613