副本的SharpJS在NodeJS中调整图像的大小?"/>
您如何使用仅具有URL的Sharp,使用async / await并没有创建本地副本的SharpJS在NodeJS中调整图像的大小?
我正在一个可用的图像处理库是NodeJS的Sharp用于缩放图像的环境中工作。由于它是基于管道的,因此一直很稳定,但是我的任务是将其转换为TypeScript,并在可能的情况下使用Async / Await进行设置。我已经准备好大多数东西,但是我面临的问题在于我所拥有的只是图像的URL,而Sharp期望字符串URI(仅本地文件)或Buffer。
[当前,我正在使用包Axios,以将图像作为可通过响应上的data
属性检索的字符串来获取。我一直在将Buffer.from(response.data)
的字符串创建的缓冲区输入Sharp,在我尝试通过尝试收集元数据来“处理”图像之前,它没有任何问题。此时,它将引发错误:[Error: Input buffer contains unsupported image format]
。但是我知道该映像是有效的,因为它在旧系统中有效,并且我没有更改任何依赖项。
我使用QuokkaJS进行测试,并且以下PoC失败,并且我需要使其正常运行。
import axios from 'axios';
import Sharp from 'sharp';
const url = '.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
}
[如果有人知道我做错了什么,或者想让我添加任何特定的信息,请告诉我!如果我需要通过管道传输图像数据,请告诉我。我试图直接通过管道将它在字符串上获得pipe is not a function
(这很有意义)。
更新#1:
非常感谢@Thee_Sritabtim的评论,它解决了问题。基本上,我一直试图将基于Stream的String转换为Buffer。相反,我需要声明该请求是针对ArrayBuffer
的,然后在声明其binary
类型的同时将其送入Sharp。 PoC的工作示例如下!
import axios from 'axios';
import Sharp from 'sharp';
const url = '.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!
}
回答如下:要从axios
响应中获取缓冲区,您必须将responseType
设置为'arraybuffer'
。
const imageResponse = await axios({url: url, responseType: 'arraybuffer'})
const buffer = Buffer.from(imageResponse.data, 'binary')
或者,>>
您还可以将流用作sharp()
的输入,因此可以将responseType
保留为'stream'
const imageResponse = await axios({url: url, responseType: 'stream'})
const src = imageResponse.data.pipe(sharp())
//...
const metadata = await src.metadata()
更多推荐
您如何使用仅具有URL的Sharp,使用async / await并没有创建本地副本的SharpJS在NodeJS中调整图像的大小?
发布评论