Get the width and height of an image in node.js
Asked Answered
R

7

91

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.

Retrogressive answered 22/9, 2012 at 1:21 Comment(1)
This appears to be a duplicate (and someone found an answer already): #5531446Retrogressive
I
44

Yes this is possible but you will need to install GraphicsMagick or ImageMagick.

I have used both and I can recommend GraphicsMagick it's lot faster.

Once you have installed both the program and it's module you 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);
  }
});
Impuissant answered 22/9, 2012 at 2:16 Comment(8)
In this case, how can I write a function that returns size.width for a given image, and invoke that function outside of the callback?Retrogressive
Also, here's a related question: #12540905Retrogressive
I have provided an answer to other question you linked to.Impuissant
Is there a way to do this without using an image library in pure JS?Spiraea
This is a great example of why you should always use curly brackets, only the first console.log is covered by the if statement.Peterkin
How would I go about using a remote URL?Crampon
Oliver, the link in the answer below this one shows an example of getting the dimensions of a remote URL.Enchorial
can anyone tell us how to get the remote URL image size please ? with 'https://' ??Complice
P
179

Installing GraphicsMagick or ImageMagick isn't at all needed, determining the dimensions of a image is as easy as looking at the header. image-size is a pure javascript implementation of said feature which is very easy to use.

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);
});
Phyllida answered 21/11, 2013 at 2:22 Comment(5)
This should be the accepted answer simply because gm/im have much more overhead than needed for this task.Salamander
There is a bug in image-size. I just experienced it in production. GraphicsMagick does not have the same bug.Psychosomatics
Not at all. image-size gives "Corrupt JPG, exceeded buffer limits" error on big jpg filesBirk
This is indeed a very good solution. And for those who require only a tiny bit of the logic for a specific format, for example, the library is very easy to extract and reduce.Lounging
If you are trying to use this in a context which doesn't allow fs or path imports, try using the buffer-image-size library instead (from this answer). It explicitly forks image-size and removes those two dependencies. Very helpful for usage in Next.js static contexts.Tizes
I
44

Yes this is possible but you will need to install GraphicsMagick or ImageMagick.

I have used both and I can recommend GraphicsMagick it's lot faster.

Once you have installed both the program and it's module you 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);
  }
});
Impuissant answered 22/9, 2012 at 2:16 Comment(8)
In this case, how can I write a function that returns size.width for a given image, and invoke that function outside of the callback?Retrogressive
Also, here's a related question: #12540905Retrogressive
I have provided an answer to other question you linked to.Impuissant
Is there a way to do this without using an image library in pure JS?Spiraea
This is a great example of why you should always use curly brackets, only the first console.log is covered by the if statement.Peterkin
How would I go about using a remote URL?Crampon
Oliver, the link in the answer below this one shows an example of getting the dimensions of a remote URL.Enchorial
can anyone tell us how to get the remote URL image size please ? with 'https://' ??Complice
L
25

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-size will help. Of course, it supports local streams too.

It's written in pure JS and does not need any heavy dependencies (ImageMagick and so on).

Lentha answered 21/4, 2016 at 1:28 Comment(1)
This should be the newly accepted answer.Explorer
C
4

Easiest way to do this with multer using buffer-image-size

I have used buffer-image-size to validate the image dimensions. I need to validate the exact image size before uploading it to the bucket.

var sizeOf = require('buffer-image-size');
var dimensions = sizeOf(yourImageBuffer);
console.log(dimensions.width, dimensions.height);

ex:

Router.js

Router.post('/upload_image',
         multerUpload.single('image'),     // multer upload configuration
         imageDimensionHandler(500,200),   // here I validate image dimension
         upload_image_controller           // controller function
       );

here is my middleware that I used after multerUpload.single('image') middleware.

imageDimensionHandler.js ( middleware )

const sizeOf = require('buffer-image-size');

const imageDimensionHandler = (width, height) => (async (req, res, next) => {
    if (req.file) {
        const fileBuffer = req.file.buffer;
        var dimensions = sizeOf(fileBuffer);

        if (width == dimensions.width && height == dimensions.height) {
            next();
        } else {
            throw new Error(`expected image size is ${condition.width} x ${condition.height} pixel.`);
        }
    } else {
        next();
    }
});

Note: please ignore it if you don't find it appropriate for you.

Cyclops answered 19/4, 2022 at 9:23 Comment(0)
S
2

Calipers is another pure Javascript library that can determine the dimensions of images.

https://github.com/calipersjs/calipers

Stoner answered 4/1, 2016 at 0:8 Comment(0)
G
2

I used Jimp: https://www.npmjs.com/package/jimp npm install --save jimp

const jimage1 = await Jimp.read(imgBuffer);
const jimage2 = await Jimp.read(imgUrl);
const width = jimage1.bitmap.width;

It's effectively a wrapper for pixel-match

Grippe answered 29/12, 2021 at 7:37 Comment(0)
S
0
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){

        }
      });
Shorthand answered 30/10, 2017 at 5:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.