Detect the width and height of images in a stream
// +-----------+
// | |
// 300px | foo.jpg |
// | |
// +-----------+
// 400px
var imageSizeStream = createImageSizeStream()
.on('size', function(dimensions) {
dimensions; //=> {width: 400, height: 300, type: 'jpg'}
stream.destroy();
});
var stream = fs.createReadStream('path/to/foo.jpg').pipe(imageSizeStream);
npm install --save image-size-stream
var createImageSizeStream = require('image-size-stream');
option: Object
Return: Object
(stream.Transform
)
The stream tries to detect the image size and emits size
or error
event.
var createImageSizeStream = require('image-size-stream');
var imageSizeStream = createImageSizeStream();
Type: Number
Default: 128 * 1024
The maximum bytes the stream can reads. It emits an error if it cannot detect the image size though it has reached the limit.
Usually the default value meets the requirements.
This event fires when the stream detect the image size. It passes an object in the form {width: [Number], height: [Number], type: [String]}
to the callback function.
type
will be one of the following strings: bmp
gif
jpg
png
psd
svg
tiff
webp
imageSizeStream.on('size', function(dimensions) {
console.log('size: ' + dimensions.width + ' x ' + dimensions.height);
console.log('image format: ' + dimensions.type);
});
This event fires when the stream failed to detect the image size. It passes an error to the callback function.
These examples show that you don't need to read the image entirely if you just want to detect its width and height.
var fs = require('fs');
var fileStream = fs.createReadStream('path/to/image.jpg');
var createImageSizeStream = require('image-size-stream');
var size = createImageSizeStream();
size
.on('size', function(dimensions) {
console.log(dimensions);
fileStream.destroy();
})
.on('error', function(err) {
throw err;
});
fileStream.pipe(size);
If you want to stop reading the rest of the image file at size
event, call fs.ReadStream#destroy() or fs.ReadStream#close().
var http = require('http');
var createImageSizeStream = require('image-size-stream');
var size = createImageSizeStream();
size
.on('size', function(dimensions) {
console.log(dimensions);
request.abort();
})
.on('error', function(err) {
throw err;
});
var request = http.get('url/to/image.png', function(response) {
response.pipe(size);
});
If you want to stop loading the rest of the image file at size
event, call request.abort().
Copyright (c) 2014 - 2015 Shinnosuke Watanabe
Licensed under the MIT License.