【轉】NodeJS 將網絡圖片轉爲base64(繞過前端跨域)

代碼以下:api

var http = require('http');

var url = 'http://thirdwx.qlogo.cn/mmopen/BEMV4WOAicktAAllnv9FdJFSU7QYVibMU62ctg7Ie5HiaCuDVCyiapibwrs48N97yrzLel03FvOUqAHEZGfBY5tCdnuHKEg4YvZSC/132';  //一張網絡圖片

http.get(url, function (res) {
    var chunks = [];
    var size = 0;
    res.on('data', function (chunk) {
        chunks.push(chunk);
        size += chunk.length;  //累加緩衝數據的長度
    });
    res.on('end', function (err) {
        var data = Buffer.concat(chunks, size);
        var base64Img = data.toString('base64');
        console.log(`data:image/png;base64,${base64Img}`);
    });
});
相關文章
相關標籤/搜索