How do I get the equivalent of a "new Image()" (and then myImage.src... etc), but on NodeJS?
Opening images on NodeJS and finding out width/height
Asked Answered
Your best bet might be to figure out how to integrate the ImageMagick (or GraphicsMagick) C runtime into Node. –
Goebbels
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 }
})
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
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)
})
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 }
})
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
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.
© 2022 - 2024 — McMap. All rights reserved.