【问题标题】:How do I scrape a PNG image and save it to my disk properly如何抓取 PNG 图像并将其正确保存到我的磁盘
【发布时间】:2021-07-01 00:43:38
【问题描述】:

我不知道如何正确下载和保存 PNG 图片。

我将尝试从这个网站获取我的个人资料图片作为示例,使用 axios:

    const fs = require("fs");
    const axios = require("axios");
    
    axios
       .get("https://i.stack.imgur.com/VQs8o.png")
       .then((res) => {
          console.log(res.data); //returns gibberish V�&ZJ���%rl�D�*=Y�����

          fs.writeFile("./profile.png", res.data, (err) => {
             if (err) console.log(err);
          });
       })
       .catch((err) => {
          if (err) console.log(err);
       });

当我将图像写入文件并尝试打开它时,它会说发生错误或它不是 PNG 文件。

当我记录收到的数据时,它显示为一堆乱码,带有如下字符:

'��BNږ��"V�&ZJ���%rl�D�*=Y�������?��w�p��}0���S�κ���u!p

我尝试将其保存到 node.js 中每个 encoding type 的文件中。我试过使用Buffer.from(),但没有任何效果。

我不知道我错过了什么。我的问题是:如何以正确的格式存储图像?为什么会出现一堆乱码,有没有办法解码成base64url?

【问题讨论】:

    标签: node.js http image-processing web-scraping axios


    【解决方案1】:

    “乱码”是因为您试图对二进制数据执行console.log()。这是意料之中的事。

    但是,显然 axios 正在对数据执行某些操作,因此您无法获得图像的确切二进制数据。可能有 axios 设置可以纠正这个问题。

    它与got() 库配合得很好,如下所示:

    const fs = require("fs");
    const got = require("got");
    const { pipeline } = require('stream')
    
    const readStream = got.stream("https://i.stack.imgur.com/VQs8o.png")
    pipeline(readStream, fs.createWriteStream("./profile.png"), (err) => {
        if (err) {
            console.log(err);
        } else {
            console.log("Write complete");
        }
    });
    

    而且,如果你告诉 axios,你想要一个流,你可以这样做:

    const fs = require("fs");
    const axios = require("axios");
    
    // GET request for remote image in node.js
    axios({
        method: "get",
        url: "https://i.stack.imgur.com/VQs8o.png",
        responseType: "stream"
    }).then(function(response) {
        response.data.pipe(fs.createWriteStream("./profile.png"))
    });
    

    【讨论】:

    • 太棒了,非常感谢。试图支持你的答案,但我不能,因为我是新来的:/
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-30
    • 1970-01-01
    • 2011-01-25
    • 2021-10-13
    • 2018-10-09
    • 2014-11-05
    相关资源
    最近更新 更多