Node.js Express App to Find Image Size From URL or From Local Computer Using image-size Library 2020

Node.js Express App to Find Image Size From URL or From Local Computer Using image-size Library 2020

 

 

 

 

Get Started

 

npm i image-size

 

 

Get Image Size From Local Computer

 

 

var sizeOf = require('image-size');

var dimensions = sizeOf('images/funny-cats.png');

console.log(dimensions.width, dimensions.height);

 

 

Asynchronous way

 

var sizeOf = require('image-size');

sizeOf('images/funny-cats.png', function (err, dimensions) {
  console.log(dimensions.width, dimensions.height);
});

 

 

Using Promises

 

 

var { promisify } = require('util');
var sizeOf = promisify(require('image-size'));
sizeOf('images/funny-cats.png')
  .then(dimensions => { console.log(dimensions.width, dimensions.height); })
  .catch(err => console.error(err));

 

 

Using Async Await

 

 

var { promisify } = require('util');
var sizeOf = promisify(require('image-size'));
(async () => {
  try {
    const dimensions = await sizeOf('images/funny-cats.png');
    console.log(dimensions.width, dimensions.height);
  } catch (err) {
    console.error(err);
  }
})().then(c => console.log(c));

 

See also  Bootstrap 4 Google Material Design Icons & Fonts Example in Browser Using HTML5 & Javascript Full Project For Beginners

 

 

Getting Size of Image From URL

 

 

var url = require('url');
var http = require('http');
 
var sizeOf = require('image-size');
 
var imgUrl = 'http://my-amazing-website.com/image.jpeg';
var options = url.parse(imgUrl);
 
http.get(options, function (response) {
  var chunks = [];
  response.on('data', function (chunk) {
    chunks.push(chunk);
  }).on('end', function() {
    var buffer = Buffer.concat(chunks);
    console.log(sizeOf(buffer));
  });
});

 

 

 

Leave a Reply