我一直在寻找一个 JavaScript 解决方案来将图像从外部 url 转换为数据 uri。我已经安装了多个软件包并测试了多种方法,但一直无法找到可用的方法。
我想要什么:
var url = 'https://static-00.iconduck.com/assets.00/npm-icon-512x512-qtfdrf37.png';
var output = convertToUri(`${url}`); // doesn't need to be a one liner just anything relatively simple that works
res.send(`${output}`);
我拥有的最接近的东西:(使用 npm 中的
data-uri
包)
var url = 'https://static-00.iconduck.com/assets.00/npm-icon-512x512-qtfdrf37.png';
data_uri.encode(=`${url}`, function(results){
console.log(results); // this comes in json form that doesn't seem to want to cooperate with JSON.parse();
// if somebody could figure this out that would be equally as helpful
// https://www.npmjs.com/package/data-uri
});
我找到了一种使用
image-to-base64
包来做到这一点的方法:
const imgtoBase64 = require('image-to-base64')
app.get('/', (req, res) => {
const URL = 'https://www.google.de/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png';
imgtoBase64(`${URL}`)
.then( (response) => {
console.log('data:image/png;base64,' + response); // the response will be the string base64.
}
)
.catch(
(error) => {
console.log(error);
}
)
});
您可以使用此代码将 url 转换为 base64 :
const fetch = require('node-fetch')
, base64stream = require('base64-stream');
const URL = 'https://www.google.de/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png';
fetch(URL)
.then((res) => {
return new Promise((resolve, reject) => {
let chunks = [];
let myStream = res.body.pipe(base64stream.encode());
myStream.on('data', (chunk) => {
chunks = chunks.concat(chunk);
});
myStream.on('end', () => {
resolve(chunks.toString('base64'));
});
});
})
.then(console.log);
来源:https://gist.github.com/muety/3ef97aad64ac733831e41ef5025133e0