使用GraphicsMagick方法取决于具有CollectionFS的维度

我正在寻找一种工作方式来使用CollectionFS transformWrite函数中的GM方法,具体取决于图像大小。 在通用汽车公司实施了一个规模的方法,但这是asynchronous的,所以它似乎是不可能的使用。

我尝试了以下内容:

gm(readStream, fileObj.name()).size(function(err, dimensions){ if (err) { console.log('err with getting size:'); console.log(err); } console.log('Result of media_size:'); console.log(dimensions); // here do smth depends on the dimensions ... gm(readStream, fileObj.name()).resize('1200', '630').stream().pipe(writeStream); }); 

当我在CollectionFS函数中使用上面的代码片段时,我得到这个错误:

错误:gm()。stream()或gm()。write()带有不可读的stream。

这似乎是一个问题,我使用asynchronousfunction – 当删除asynchronousfunction的上传完美的作品,但我没有访问上传图像的尺寸。

是否有一种解决scheme,以fileObj访问fileObjreadStreamwriteStream时获取图像的维度同步?

编辑:

感谢Jasper与wrapAsync的提示。 我testing了它,并使用这个代码:

 var imgsize; var img = gm(readStream, fileObj.name()); imgsize = Meteor.wrapAsync(img.size, img); console.log('call wrapAsync:'); var result; try { result = imgsize(); } catch (e) { console.log('Error:'); console.log(e) } console.log('((after imgsize()))'); 

当看一下console.logs脚本在“call wrapAsync”后停止 – 也没有错误返回,所以很难说出什么问题。 我也尝试过使用Meteor.wrapAsync(imagesize);的NPM包“imagesize” Meteor.wrapAsync(imagesize); 然后imgsize(readStream)导致相同:“call wrapAsync:”之后没有控制台日志。

问题的核心不是gm().size()的asynchronous行为,而是使用readStream两次。 首先你使用它来获取图像的大小,这将清空readStream 。 然后,您尝试再次使用它来resize,但因为它已经结束,您会看到一个错误,告诉您该stream是不可读的。

我在gm包stream文件的底部find了解决scheme:

GOTCHA:在处理inputstream和任何“识别”操作(大小,格式等)时,如果还需要将图像转换(写入()或stream()),则必须通过“{bufferStream:true}” :这缓冲了内存中的readStream!

基于以下小例子,我们可以将您的代码更改为:

 gm(readStream, fileObj.name()).size({ bufferStream: true }, function(err, dimensions){ if (err) { console.log('err with getting size:'); console.log(err); } console.log('Result of media_size:'); console.log(dimensions); // here do smth depends on the dimensions ... this.resize('1200', '630').stream().pipe(writeStream); }); 

在callback的内部, this是指你正在处理的图像,你可以用它来继续你的链。

我在一个小样本的meteor应用程序中testing了它,并且工作正常!