我工作的环境中可用的图像处理库是 NodeJSSharp https://github.com/lovell/sharp用于缩放图像。它一直很稳定,因为它是基于管道的,但我的任务是将其转换为 TypeScript,并在可能的情况下使用 Async/Await 进行设置。我已准备好大部分内容,但我面临的问题在于,我所拥有的只是图像的 URL,而 Sharp 需要字符串 URI(仅限本地文件)或缓冲区。
目前,我正在使用该包Axios https://github.com/axios/axios为了将图像作为可检索的字符串来获取data
响应上的属性。我一直在提供从字符串创建的缓冲区Buffer.from(response.data)
进入夏普,它没有任何问题,直到我尝试通过尝试收集元数据来“处理”图像。此时会抛出错误:[Error: Input buffer contains unsupported image format]
。但我知道该映像是有效的,因为它在旧系统中工作,并且我没有更改任何依赖项。
我使用 QuokkaJS 进行测试,以下 PoC 失败,我需要让它恢复正常运行。
import axios from 'axios';
import Sharp from 'sharp';
const url = 'https://dqktdb1dhykn6.cloudfront.net/357882-TLRKytH3h.jpg';
const imageResponse = await axios({url: url, responseType: 'stream'});
const buffer = Buffer.from(imageResponse.data);
let src = new Sharp(buffer);
const src2 = src.clone();//this is simply because it will end up being a loop, if this is the issue let me know.
try {
await src2.jpeg();
await src2.resize(null, 1920);
await src2.resize(1080, null);
const metadata = await src2.clone().metadata();//this is where it fails
console.log(metadata);
} catch(e) {
console.log(e);//logs the mentioned error
}
如果有人知道我做错了什么,或者有任何他们希望我添加的具体信息,请告诉我!如果我need要通过管道传输图像数据,请告诉我。我尝试过直接通过管道获取pipe is not a function
在字符串上(这是有道理的)。
更新#1:
非常感谢@Thee_Sritabtim 的评论,它解决了这个问题。基本上,我一直在尝试将基于流的字符串转换为缓冲区。我需要声明该请求是为了ArrayBuffer
,然后将其输入 Sharp,同时声明其类型binary
。 PoC 的工作示例如下!
import axios from 'axios';
import Sharp from 'sharp';
const url = 'https://dqktdb1dhykn6.cloudfront.net/357882-TLRKytH3h.jpg';
const imageResponse = await axios({url: url, responseType: 'arraybuffer'});
const buffer = Buffer.from(imageResponse.data, 'binary');
let src = new Sharp(buffer);
try {
await src.jpeg();
await src.resize(null, 1920);
await src.resize(1080, null);
const metadata = await src.metadata();//this was where it failed, but now it prints an object of metadata
console.log(metadata);
} catch(e) {
console.log(e);//Doesn't catch anything any more!
}