【问题标题】:Downloading and resizing an image with Axios/Sharp使用 Axios/Sharp 下载和调整图像大小
【发布时间】:2019-11-15 07:59:04
【问题描述】:

我目前正在尝试使用 Axios 下载图像,然后调整结果大小并通过 Node 在 GraphQL 解析器中将其保存在本地。

这是我正在使用的代码块:

axios.get(url)
    .then((response) => {
        const { set, collector_number } = response.data;
        const sourceUrl = response.data.image_uris.border_crop;
        const filename = `${set}/${collector_number}.png`;
        axios.get(sourceUrl, { responseType: 'arraybuffer' })
            .then((res) => {
                console.log(`Resizing Image!`)
                sharp(res)
                    .resize(226, 321)
                    .toFile(`../cardimg/${filename}`)
                    .then(() => {
                        console.log(`Image downloaded and resized!`)
                    })
                    .catch((err) => {
                        console.log(`Couldn't process: ${err}`);
                    })
            })
    })

当我执行代码(通过 GraphQL Mutation)时,它会抛出一个错误,指出:Input file is missing

不确定是滥用 Axios,还是我对 Sharp 做错了什么。

有什么建议吗?我最初担心我需要弄乱来自 HTTP 请求的响应格式,但据我所知,我做得对。

提前致谢!

我使用了console.log来确保它确实在抓取图像并且URL是正确的,所以已经测试过了,所以sourceUrl确实在抓取图像,我只是不知道如何正确地做任何事情-with- 我正在抓取的数据。

【问题讨论】:

  • 你能把sharp(res)改成sharp(res.data)吗?因为res 包含除数据之外的大量其他键。像header之类的
  • 如果这不起作用,请尝试sharp(new Blob([res.data], { type: 'image/png'})) 并检查
  • 这绝对是因为我在第二个请求中没有使用.data!如果您将此作为解决方案,我会接受,这是我的疏忽。谢谢!
  • 作为答案添加,也链接了承诺。

标签: node.js axios sharp


【解决方案1】:

axios 返回完整的响应正文,例如 statusheadersconfig。响应正文在 .data 键中。因此,在您的情况下,它将是:

axios.get(..).then((res) => { sharp(res.data)})

另外,Promise 中的 Promise 被认为是反模式,你可以很容易地链接它。

let fileName;
axios.get(url)
  .then((response) => {
    const { set, collector_number } = response.data;
    const sourceUrl = response.data.image_uris.border_crop;
    filename = `${set}/${collector_number}.png`;
    return axios.get(sourceUrl, { responseType: 'arraybuffer' })
  })
  .then((res) => {
    console.log(`Resizing Image!`)
    return sharp(res.data)
      .resize(226, 321)
      .toFile(`../cardimg/${filename}`)
  })
  .then(() => {
    console.log(`Image downloaded and resized!`)
  })
  .catch((err) => {
    console.log(`Couldn't process: ${err}`);
  })

【讨论】:

  • 我实际上并没有意识到这是真的,并且出于某种原因(我仍在学习 Promises),我不知道你可以这样链接它们。万分感谢!接受!
猜你喜欢
  • 1970-01-01
  • 2022-09-23
  • 2021-04-25
  • 1970-01-01
  • 2017-01-01
  • 2019-05-17
  • 1970-01-01
  • 1970-01-01
  • 2019-08-18
相关资源
最近更新 更多