简体   繁体   English

如何将远程图像读取到 base64 数据 url

[英]How to read remote image to a base64 data url

actually there are many answers for this question.其实这个问题有很多答案。 But my problem is, i want to generate pdf dynamically with 5 external(URL) images.但我的问题是,我想用 5 个外部(URL)图像动态生成 pdf。 Im using PDFmake node module.我正在使用 PDFmake 节点模块。 it supports only two ways local and base64 format.它仅支持本地和 base64 格式两种方式。 But i don't want to store images locally.但我不想在本地存储图像。 so my requirement is one function which takes url as parameter and returns base64.所以我的要求是一个以 url 作为参数并返回 base64 的函数。 so that i can store in global variable and create pdfs这样我就可以存储在全局变量中并创建 pdf

thanks in advance提前致谢

function urlToBase(URL){
return base64;
}

var img = urlToBase('https://unsplash.com/photos/MVx3Y17umaE');
var dd = {
            content: [
              {
                text: 'fjfajhal'
              },
              {
                image: img,
              }
            ]
          };

          var writeStream = fs.createWriteStream('myPdf.pdf');
        var pdfDoc = printer.createPdfKitDocument(dd);
        pdfDoc.pipe(writeStream);
        pdfDoc.end();

im using PDFmake module from npm我正在使用 npm 中的 PDFmake 模块

The contents of the remote image can first be fetched with an HTTP request, for example using the ubiquitous request npm module.远程图像的内容可以首先通过 HTTP 请求获取,例如使用无处不在的request npm 模块。 The image string contents can then be transformed to a buffer and finally converted to a base64 string.然后可以将图像字符串内容转换为buffer ,最后转换为 base64 字符串。 To complete the transformation, add the proper data-url prefix , for example, data:image/png,base64, to the beginning of the base64 string.要完成转换,请在 base64 字符串的开头添加适当的data-url 前缀,例如data:image/png,base64,

Here is a rough example for a PNG image:以下是 PNG 图像的粗略示例:

const request = require('request-promise-native');

let jpgDataUrlPrefix = 'data:image/png;base64,';
let imageUrl         = 'https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png';

request({
    url: imageUrl,
    method: 'GET',
    encoding: null // This is actually important, or the image string will be encoded to the default encoding
})
    .then(result => {
        let imageBuffer  = Buffer.from(result);
        let imageBase64  = imageBuffer.toString('base64');
        let imageDataUrl = jpgDataUrlPrefix+imageBase64;

        console.log(imageDataUrl);
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM