首页 > 解决方案 > 调整来自 API 的图像大小

问题描述

我正在调用 API 来获取一些图像。返回的图像都有不同的宽度和高度。我尝试在前端更改它们,使用 HTML img 宽度和高度属性,但它们不起作用。因此,我尝试使用用于调整图像大小的 npm package sharp。但它给出了这个错误:“输入文件丢失”。这是为什么?任何帮助表示赞赏

代码如下:

exports.apiMeme = catchAsync(async (req, res, next) => {
    let apiImgs = []
    let url = 'https://api.imgflip.com/get_memes'
    let baseUrl = process.env.ENDPOINT
    let data = await fetch(new URL(url, baseUrl, {
        method: 'GET',
        encoding: null
    }))
    await data.json().then(response => {
        response.data.memes.forEach(m => {
            apiImgs.push(m.url)
            sharp(m.url)
            .rotate()
            .resize(200)
            .jpeg({ mozjpeg: true })
            .toBuffer()
            .then(data => apiImgs.push(data))
            .catch(err => console.log(err));
        })
          res.status(200).json({ apiImgs })
})
})

标签: node.jsimageapisharp

解决方案


推荐阅读