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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5530946/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 17:31:42  来源:igfitidea点击:

Opening images on NodeJS and finding out width/height

javascriptimagenode.js

提问by Mamsaac

Thanks a lot in advance for the future help. What I need is the equivalent of a "new Image()" (and then myImage.src... etc) but on NodeJS. I will thank whoever answers quickly deep in my heart... and well, also saying "thanks!" :P

非常感谢您对未来的帮助。我需要的是相当于“new Image()”(然后是 myImage.src ... 等)但在 NodeJS 上。我会在内心深处感谢快速回答的人......好吧,也说“谢谢!” :P

回答by Linus Unneb?ck

Using imagemagickfor this is very overkill since you only want to read the header of the file and check the dimensions. image-sizeis a pure javascript implementation of said feature which is very easy to use.

使用imagemagick它是非常矫枉过正的,因为您只想读取文件的标题并检查尺寸。image-size是上述功能的纯 javascript 实现,非常易于使用。

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

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)
})

回答by John Flatness

There's node-imagemagick, (you'll need to have ImageMagick, obviously).

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 }
})

回答by Vitaly

https://github.com/nodeca/probe-image-sizethat should help. Small + sync/async modes + urls support.

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

var probe = require('probe-image-size');

// Get by URL
//
probe('http://example.com/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' }

Disclaimer: I am the author of this code.

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