Git Product home page Git Product logo

image-size's Introduction

image-size

Build Status Package Version Downloads

A Node module to get dimensions of any image file

Supported formats

  • BMP
  • CUR
  • DDS
  • GIF
  • HEIC (HEIF, AVCI, AVIF)
  • ICNS
  • ICO
  • J2C
  • JP2
  • JPEG
  • KTX (1 and 2)
  • PNG
  • PNM (PAM, PBM, PFM, PGM, PPM)
  • PSD
  • SVG
  • TGA
  • TIFF
  • WebP

Programmatic Usage

npm install image-size --save

or

yarn add image-size

Synchronous

const sizeOf = require("image-size")
const dimensions = sizeOf("images/funny-cats.png")
console.log(dimensions.width, dimensions.height)

Asynchronous

const sizeOf = require("image-size")
sizeOf("images/funny-cats.png", function (err, dimensions) {
  console.log(dimensions.width, dimensions.height)
})

NOTE: The asynchronous version doesn't work if the input is a Buffer. Use synchronous version instead.

Also, the asynchronous functions have a default concurrency limit of 100 To change this limit, you can call the setConcurrency function like this:

const sizeOf = require("image-size")
sizeOf.setConcurrency(123456)

Using promises (nodejs 10.x+)

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

Async/Await (Typescript & ES7)

const { promisify } = require("util")
const 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))

Multi-size

If the target file is an icon (.ico) or a cursor (.cur), the width and height will be the ones of the first found image.

An additional images array is available and returns the dimensions of all the available images

const sizeOf = require("image-size")
const images = sizeOf("images/multi-size.ico").images
for (const dimensions of images) {
  console.log(dimensions.width, dimensions.height)
}

Using a URL

const url = require("url")
const http = require("http")

const sizeOf = require("image-size")

const imgUrl = "http://my-amazing-website.com/image.jpeg"
const options = url.parse(imgUrl)

http.get(options, function (response) {
  const chunks = []
  response
    .on("data", function (chunk) {
      chunks.push(chunk)
    })
    .on("end", function () {
      const buffer = Buffer.concat(chunks)
      console.log(sizeOf(buffer))
    })
})

You can optionally check the buffer lengths & stop downloading the image after a few kilobytes. You don't need to download the entire image

Disabling certain image types

const imageSize = require("image-size")
imageSize.disableTypes(["tiff", "ico"])

Disabling all file-system reads

const imageSize = require("image-size")
imageSize.disableFS(true)

JPEG image orientation

If the orientation is present in the JPEG EXIF metadata, it will be returned by the function. The orientation value is a number between 1 and 8 representing a type of orientation.

const sizeOf = require("image-size")
const dimensions = sizeOf("images/photo.jpeg")
console.log(dimensions.orientation)

Command-Line Usage (CLI)

npm install image-size --global

or

yarn global add image-size

followed by

image-size image1 [image2] [image3] ...

Credits

not a direct port, but an attempt to have something like dabble's imagesize as a node module.

image-size's People

Contributors

adamrenklint avatar bahmutov avatar borodean avatar chrisvxd avatar duncanbeevers avatar evert avatar forbeslindesay avatar fregante avatar hupfis avatar jiang-xuan avatar jorrit avatar josh-cena avatar jushar avatar kornelski avatar linusu avatar mannyclicks avatar netroy avatar ntnz avatar renovate-bot avatar rkrol avatar rossj avatar shinnn avatar swftvsn avatar vampirical avatar vinicius0026 avatar yous avatar zanehannanau avatar zcei avatar zeke avatar zzahos-kg avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

image-size's Issues

Files never closed, leading to Error: EMFILE, too many open files

I'm getting a bug on OS X: Error: EMFILE, too many open files after the server runs for a while.
It looks like you need to close files after reading from them:

fs.read(descriptor, buffer, 0, bufferSize, 0, function (err) {
  if (err) { throw err; }
  // no errors, return the buffer
  fs.close(descriptor, function(err) {
    if (err) { throw err; }
    callback();
  });
});

Support for .ico

As long as webpack-favicon-plugin uses image-size could you add support for .ico format?

Now when I try to run with favicon.ico get
node_modules/image-size/lib/index.js:34 throw new TypeError('unsupported file type');

iPhone picture rotation

When detecting the size of an iPhone (6) image, it always returns 3264 x 2448, even when it's a portrait image.

It should understand the orient information from the Exif data.

Getting "unsupported file type" error on valid images

When trying to get size information from the attached image. I'm getting an "unsupported file type" error.

If it's relevant, I've downloaded this image from my facebook album. I'm getting the same error with other facebook images.

1472743_634450849946235_659823690_n

TypeError: invalid jpg

I have a bunch of .jpg images which I saved from Photoshop CS6. But for all of them I get this error, so I can’t process them. When I tried to process sample image from repository - it worked.

[TypeError: Corrupt JPG, exceeded buffer limits]

Trying to calculate the following image throws an exception:

var imagesize = require("image-size");
var url = "http://www.niemanlab.org/images/renewalinvoice.jpg";
var needle = require('needle');

var stream = needle.get(url);
stream.on('readable', function( ) {
    var chunk;
    while( chunk = this.read() ) {
        info = imagesize(chunk);
        if( info ) {
            stream.end();
            console.log('streaming picture', info);
        }
    }
});
stream.on('end', function(){
    console.log('Stream ended');
});

TypeError

open a normal jpg image, got the error "Invalid JPG, marker table corrupted"

browser support (again)

Hello,

Sorry to ask again for browser support but the solution you suggested (new Image ...) does not work in web workers.

There are libraries compatibles such as png.js and jpg.js but I could not find a way to get the size of a picture.

Best,

Guillaume Leclerc

Request HTTPS support

I get this when using an HTTPS link:

http.js:1840
    throw new Error('Protocol:' + options.protocol + ' not supported.');

JPEG vs JPG in content type

Hi,

Just wondering what the best approach is to resolve this issue:

We have images that are being uploaded and the content type is being set as image/jpeg but your valid types only include jpg. Should I create a pull request to add this type with additional test cases?

other formats might include:

jpg
.jpeg
.jpe
.jif
.jfif
.jfi

Thanks.

John

Url becomes Local path

I have got problem that given a URL of an image, but the url turns to local path in sizeOf( )

================== my code ===============

var imgUrl = 'https://abe/photo.jpg';
sizeOf(imgUrl, function(err, dimensions, length) {
  console.log(err, dimensions, length);
});

================= Error Msg ==============

GET /2 200 22.530 ms - 210
{ [Error: ENOENT: no such file or directory, open '/Users/abc/Desktop/node/image_size/https://abe/photo.jpg']

Sizing up remote Web images

Have you ever thought of allowing a URLs of remote images in addition to paths to local ones? Would you accept a pull request or do you picture that (pun intended) as a different module all together?

var sizeOf = require('image-size');
sizeOf('http://example.com/images/funny-cats.png', function (err, dimensions) {
  console.log(dimensions.width, dimensions.height);
});

SVG dimensions get (wrongly) rounded

I tried using image-size with (autogenerated) SVG files that specify their dimensions in ex units, such as:

<svg width="69.167ex" height="2.667ex" viewBox="0 -904.8 29770.5 1176.8">
...
</svg>

but the dimensions get reported as being width 69 and height 2, with the rather important decimal fraction part removed. For bitmap images this makes sense, but for SVG this means the dimensions are very wrong and cannot be relied upon.

Worth not rounding dims for vector format images?

support promises

i'd like to use this asynchronously with promises, instead of the nodejs style callback. currently i'm manually promisifying the async version.

Use in browser context

Would be nice to use this in the browser context, which right now fails due to fs requirement not being met in the browser.

I am trying to use it with webpack. I could use image.onload but that loads the entire image versus just sniffing the image headers from the first couple of bytes without loading the entire image.

Transfering the ownership of this project

Unfortunately, I don't have the time or the energy to participate in this project anymore, so I'm looking for people who'd like to take over this project.
I've already moved the project to an independent organisation & added some previous contributors to this organisation.

I've also added @zeke as an owner on github, as well as on npm.

My deepest apologies for not being available for a long time; Didn't expect this repo to get so much traction.

//cc @shinnn @LinusU @borodean

browser support?

can i use this via browserify or something and use array buffers and such??

Fails on SVG assets without `width` and `height` properties

Using a tool like Adobe Illustrator to create SVG assets, you get output that does not include width or height properties. Here is a sample of that output, after being compressed with imagemin:

<svg xmlns="http://www.w3.org/2000/svg" viewBox="-15.6 130.7 612 507" enable-background="new -15.6 130.7 612 507"></svg>

Running through the w3c validator, this is valid SVG 1.1.

But when I run through sizeOf, I get the following error:

Uncaught TypeError: invalid svg

If I manually add the width and height attributes, sizeOf works as expected:

<svg xmlns="http://www.w3.org/2000/svg" width="612" height="507" viewBox="-15.6 130.7 612 507" enable-background="new -15.6 130.7 612 507"></svg>

The width and height attributes are described in the viewBox attribute already, as the last two values. I suggest pulling from those values if the width and height attributes are not present.

guetzli support?

Image-size is throwing an error (well, crashing on me) when I try to get the image size of a JPEG made with Google's guetzli compressor. https://github.com/google/guetzli. So far, I can't tell if this is simply this image or all guetzli processed images.

sizeOf async version crash!

sizeOf crash when i submit corrupted file such as changing the extension of exe and make it jpg. It gives the following error
error

It would be much nicer if it returns an error instead of crashing the hole thing :)

Thanks

Consider using static require dependencies

There is an issue when using the package with https://github.com/jspm (sytemjs)
jspm/registry#221

this code uses dynamic requires
https://github.com/netroy/image-size/blob/master/lib/index.js#L6-L15

and https://github.com/systemjs/systemjs can not handle it.

Actually it is importaint as image-size is used with css precompilers (such as LESS) and they have to be used in systemjs-builder worflow.

Would you consider chanding requires to static paths? Or addings static deps declarations in the beginning of the file?

example request

Please add an example of how to check size of image uploaded via express.js

Should not throw error if callback provide

function lookup throws error, but the image-size module could use callbak, if callback provide, lookup should callback the errors instead of throw it.

You can test on any unsupported files with a callback function.

v0.2.0

From #2

  • add buffer support without breaking the API

From #3

  • match the code style
  • fix the specs
  • move the detection code to where it belongs.
  • remove the license/copyright info from jpg.js
  • Add a MIT license file
  • Add a contributors section to the readme including your name

Others

  • handle a dozen type of jpeg formats
  • get sidekickjs debt down to zero, refactor jpg.js
  • Tiff support
  • WebP support #14

unsupported file type: undefined (file: undefined)

I get the following error when I try to get the image size of select images:

unsupported file type: undefined (file: undefined)

Below are a list of two of the image in question:

Most other images work. To note these are both from wordpress sites. The images were saved out of Photoshop (Save for Web & Devices) which means they were properly compressed and then uploaded to Wordpress.

Any help appreciated!

Fails build on travis - cannot find module.

I have created a docker image using this module, and when I run the code in a ubuntu docker container, it complains that it cannot find the module. The same happens when it is run directly on a linux machine.

Do you have any idea why it cannot find the module although it is in the package.json file?

The error output is :
Error: Cannot find module 'image-size' at Function.Module._resolveFilename (module.js:338:15) at Function.Module._load (module.js:280:25) at Module.require (module.js:364:17) at require (module.js:380:17) at Object.<anonymous> (/home/image-resizer/index.js:20:14) at Module._compile (module.js:456:26) at Object.Module._extensions..js (module.js:474:10) at Module.load (module.js:356:32) at Function.Module._load (module.js:312:12) at Function.Module.runMain (module.js:497:10)

The module I am using your module in can be found at https://github.com/hevnly/image-resizer#mac-users

Documentation improvement about "stop downloading the image after a few kilobytes"

Hello.
In "usage" doc, when you say:
"You can optionally check the buffer lengths & stop downloading the image after
a few kilobytes. You don't need to download the entire image"
Could you be most explicit about how many (minimum) kb per file type is required to
detect image dimensions?
Could you update the documentation, with that info and an example?
Thanks in advance.

A better api for this module

would be a streaming interface, which fires a 'dimension' or 'size' event when it was able to detect the size and stops piping from the readable stream.

This way I don't need to guess how much of the file should I download and it will always download the minimum, so faster per default.

Corrupt JPG, exceeded buffer limits on 0.6.0 version

When I uploaded specify image I got this error on 0.6.0 version, image like this

the error info is

TypeError: Corrupt JPG, exceeded buffer limits
    at validateBuffer (D:\dev\github\auto-pages\node_modules\image-size\lib\types\jpg.js:23:11)
    at Object.calculate (D:\dev\github\auto-pages\node_modules\image-size\lib\types\jpg.js:42:5)
    at lookup (D:\dev\github\auto-pages\node_modules\image-size\lib\index.js:26:31)
    at module.exports (D:\dev\github\auto-pages\node_modules\image-size\lib\index.js:101:12)
    at app.post (D:\dev\github\auto-pages\build\dev-server.js:151:20)
    at Layer.handle [as handle_request] (D:\dev\github\auto-pages\node_modules\express\lib\router\layer.js:95:5)
    at next (D:\dev\github\auto-pages\node_modules\express\lib\router\route.js:137:13)
    at Immediate.<anonymous> (D:\dev\github\auto-pages\node_modules\multer\lib\make-middleware.js:53:37)
    at runCallback (timers.js:655:20)
    at tryOnImmediate (timers.js:624:5)
    at processImmediate [as _immediateCallback] (timers.js:596:5)

Catch 'Corrupt JPG, exceeded buffer limits'

Hi,
Currently i'm developing a node js application to upload files to AWS.
I'm using a buffer to get the width and height of an image using sizeOf(file.buffer). Some files may be corrupted or damaged, for this scenario i want to set the height and width to zero.

How can i catch the TypeError before my application fail?
Thanks.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.