Opening images on NodeJS and finding out width/height
Asked Answered
C

3

17

How do I get the equivalent of a "new Image()" (and then myImage.src... etc), but on NodeJS?

Calamondin answered 3/4, 2011 at 16:43 Comment(1)
Your best bet might be to figure out how to integrate the ImageMagick (or GraphicsMagick) C runtime into Node.Goebbels
J
16

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

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 }
})
Juliannejuliano answered 3/4, 2011 at 17:9 Comment(2)
Zerosocrates, can I have your children? HAHA Sorry, I haven't slept and I got stomachache :( but at least I'm programming and there's pizza.Calamondin
@john-flatness Any idea how to do that in memory?Mobley
B
23

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

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)
})
Buran answered 21/11, 2013 at 2:20 Comment(0)
J
16

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

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 }
})
Juliannejuliano answered 3/4, 2011 at 17:9 Comment(2)
Zerosocrates, can I have your children? HAHA Sorry, I haven't slept and I got stomachache :( but at least I'm programming and there's pizza.Calamondin
@john-flatness Any idea how to do that in memory?Mobley
P
3

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

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.

Poyang answered 25/6, 2016 at 15:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.