简体   繁体   English

下载API返回的图像

[英]Download the image returned by an API

I am working with the sportradar api. 我正在使用sportradar api。 The api call that I am making, returns a png image. 我正在进行的api调用返回png图像。 Till now I have done this. 到目前为止,我已经做到了。

    const apiCall = (url) => {
        return axios.get(url).then((data) => {
            if(data){
                return Promise.resolve(data);
            }
            else{
                return Promise.reject();
            }
        });
    }

    //all data in data.assetlist
    for(let i=0; i<data.assetlist.length; i++){
        let imageLink = data.assetlist[i].links[12].href;
        let url = `https://api.sportradar.us/nfl-images-p3/ap_premium${imageLink}?api_key=${api_key}`;
        apiCall(url).then((data) => {
            console.log(data);
            let blob = new Blob(data, {type: "image/png"}); // didn't compile with this line

        });
   }

The above code is working fine and is returning the data. 上面的代码工作正常,正在返回数据。 But the data are weird character, which if I am understanding it correctly, is because of the fact that image is a blob type and I am getting a stream of data. 但是数据是奇怪的字符,如果我正确理解的话,是因为图像是Blob类型,而且我正在获取数据流。

I took reference from here and wrote this line 我从这里参考并写了这行

let blob = new Blob(data, {type: "image/png"});

I didn't try this, because I am afraid that the data is so big that it might crash my system (old laptop). 我没有尝试过,因为恐怕数据量太大,可能会损坏我的系统(旧笔记本电脑)。 If I am doing this right, I wanna know, how to save this blob file into my system as a png file and if not then I wanna know how can i convert this stream of data into an image and can download and save it in a local directory. 如果我做对了,我想知道如何将该Blob文件另存为png文件到我的系统中,否则我想知道如何将这些数据流转换为图像并可以下载并将其保存在本地目录。

If the image you get is already a blob you can download it using this library : https://github.com/eligrey/FileSaver.js 如果获取的图像已经是斑点,则可以使用以下库下载该图像: https : //github.com/eligrey/FileSaver.js

let FileSaver = require('file-saver');
FileSaver.saveAs(blob, "my_image.png");

I think you shouldn't be so worried about the size and just go for it. 我认为您不应该太担心大小而已。

After a lot of research, I found this solution and it worked. 经过大量的研究,我找到了这种解决方案,并且有效。

apiCall(url).then((response) => {
        response.data.pipe(fs.createWriteStream('test.jpg'));
    });

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

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