在 node.js 中获取图像的宽度和高度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12539918/
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
Get the width and height of an image in node.js
提问by Anderson Green
Is it possible to get the width and height of an image in node.js (on the server side, not the client side)? I need to find the width and height of an image in a node.js library that I'm writing.
是否可以在 node.js 中获取图像的宽度和高度(在服务器端,而不是客户端)?我需要在我正在编写的 node.js 库中找到图像的宽度和高度。
采纳答案by saeed
Yes this is possible but you will need to install GraphicsMagickor ImageMagick.
是的,这是可能的,但您需要安装GraphicsMagick或ImageMagick。
I have used both and I can recommend GraphicsMagick it's lot faster.
我两个都用过,我可以推荐 GraphicsMagick,它要快得多。
Once you have installed both the program and it's moduleyou would do something like this to get the width and height.
一旦你安装了程序和它的模块,你就可以做这样的事情来获得宽度和高度。
gm = require('gm');
// obtain the size of an image
gm('test.jpg')
.size(function (err, size) {
if (!err) {
console.log('width = ' + size.width);
console.log('height = ' + size.height);
}
});
回答by Linus Unneb?ck
Installing GraphicsMagickor ImageMagickisn't at all needed, determining the dimensions of a image is as easy as looking at the header. image-sizeis a pure javascript implementation of said feature which is very easy to use.
安装GraphicsMagick或ImageMagick根本不需要,确定图像的尺寸就像查看标题一样简单。image-size是上述功能的纯 javascript 实现,非常易于使用。
https://github.com/netroy/image-size
https://github.com/netroy/image-size
var sizeOf = require('image-size');
sizeOf('images/funny-cats.png', function (err, dimensions) {
console.log(dimensions.width, dimensions.height);
});
回答by Vitaly
https://github.com/nodeca/probe-image-size
https://github.com/nodeca/probe-image-size
More interesting problem is "how to detect image size without full file download from remote server". probe-image-sizewill help. Of course, it supports local streams too.
更有趣的问题是“如何在没有从远程服务器下载完整文件的情况下检测图像大小”。probe-image-size会有所帮助。当然,它也支持本地流。
It's written in pure JS and does not need any heavy dependencies (ImageMagick and so on).
它是用纯 JS 编写的,不需要任何重度依赖(ImageMagick 等)。
回答by Marcus
Calipers is another pure Javascript library that can determine the dimensions of images.
Calipers 是另一个可以确定图像尺寸的纯 Javascript 库。
回答by VIKAS KOHLI
var sizeOf = require('image-size');
sizeOf(my_file_item.completeFilename, function (err, dimensions) {
try{
if(!err){
let image_dimensions = dimensions || "";
let width = 200; // we want 200
let height = parseInt(width/(image_dimensions.width/image_dimensions.height));
}else{
}
// console.log(ex);
}catch(ex){
}
});

