我可以使用node-gm在内存中调整图像的大小,还是我需要先保存它

Can I use node-gm to resize an image in memory or do I need to save it first?

本文关键字:保存 node-gm 可以使 内存 图像 调整 我可以      更新时间:2023-09-26

我允许用户上传头像,但我想在上传时调整它们的大小。现在,gm似乎让我在调整文件大小之前先将文件保存到磁盘上。是否有可能在传入请求时调整它的大小?

像这样:

 var readStream = fs.createReadStream(req.files['profile-picture']['path']);
 gm(req.files['profile-picture']['path'], 'img.jpg')
 .write('/path/to/directory/img.jpg', function (err) {
   if (!err) console.log('done');
 });

你可以通过gm管道传输流,而不需要将文件保存到磁盘上!你甚至可以一个接一个地做几个操作,因为gm函数是可链接的(在我的例子中,我调整了图像的大小,然后从中间裁剪它(因此重力函数)

gm(req.files['profile-picture']['path'], 'img.jpg')
  .resize("100^", "100^")
  .gravity('Center')
  .crop(100, 100)
  .stream(function (err, stdout, stderr) {
     // do whatever you want with your output stream (stdout) here
  });