19

So I have a sample.jpg file and I want to check its dimensions.

The desired logic goes like this:

var img = require('./sample.jpg');
console.log(typeof img) // returns string -> Image
console.log(img.height) // returns number -> 300
console.log(img.width)  // returns nubmer -> 250

Never mind the return of the typeof. I just wan't to get the dimensions. But that is the simple break down of what where I am going. Is there a way to do this using node or plain js?

Krisztián Balla
  • 19,223
  • 13
  • 68
  • 84
  • 2
    There seems to be a popular [node package to do that](https://www.npmjs.com/package/image-size) – Nick Oct 12 '17 at 18:43

4 Answers4

44

You can use image-size npm module:

npm install image-size --save

Then can get dimentions like this:

var sizeOf = require('image-size');
var dimensions = sizeOf('./sample.jpg');
console.log(dimensions.width, dimensions.height);

For more information go through image-size documentations

kgangadhar
  • 4,886
  • 5
  • 36
  • 54
6

You can use GraphicsMagick or ImageMagick. I recommend GraphicsMagick as it's lot faster.

Install the npm package gm and use like this:

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);
  }
});
KyleMit
  • 30,350
  • 66
  • 462
  • 664
0

You can use jpeg-js.

From their docs:

var jpeg = require('jpeg-js');
var jpegData = fs.readFileSync('grumpycat.jpg');
var rawImageData = jpeg.decode(jpegData);
console.log(rawImageData);
mkhanoyan
  • 1,958
  • 18
  • 15
-3

You can use this using JS (only works in browser)

 var img = new Image();
 img.src = './sample.jpg';
 console.log(img.height);
 console.log(img.width);

For node, you can install canvas library.

Himan
  • 379
  • 1
  • 7
  • yes I tried that, it gave me this error: ReferenceError: Image is not defined at Object. (C:\Users\marvenwilsons\Desktop\h\id.js:1286:15) at Module._compile (module.js:570:32) at Object.Module._extensions..js (module.js:579:10) at Module.load (module.js:487:32) at tryModuleLoad (module.js:446:12) at Function.Module._load (module.js:438:3) at Module.runMain (module.js:604:10) at run (bootstrap_node.js:389:7) at startup (bootstrap_node.js:149:9) at bootstrap_node.js:504:3 – Marven Wilson S Donque Oct 12 '17 at 18:46