diff --git a/README.md b/README.md index 9271d176..8cda96b6 100755 --- a/README.md +++ b/README.md @@ -9,15 +9,17 @@ The typical use case for this high speed Node.js module is to convert large images of many formats to smaller, web-friendly JPEG, PNG and WebP images of varying dimensions. -The performance of JPEG resizing is typically 8x faster than ImageMagick and GraphicsMagick, based mainly on the number of CPU cores available. Everything remains non-blocking thanks to _libuv_ and Promises/A+ are supported. +The performance of JPEG resizing is typically 8x faster than ImageMagick and GraphicsMagick, based mainly on the number of CPU cores available. -This module supports reading and writing images of JPEG, PNG and WebP to and from both Buffer objects and the filesystem. It also supports reading images of many other types from the filesystem via libmagick++ or libgraphicsmagick++ if present. +Memory usage is kept to a minimum, no child processes are spawned, everything remains non-blocking thanks to _libuv_ and Promises/A+ are supported. + +This module supports reading and writing JPEG, PNG and WebP images to and from Streams, Buffer objects and the filesystem. It also supports reading images of many other types from the filesystem via libmagick++ or libgraphicsmagick++ if present. When generating JPEG output all metadata is removed and Huffman tables optimised without having to use separate command line tools like [jpegoptim](https://github.com/tjko/jpegoptim) and [jpegtran](http://jpegclub.org/jpegtran/). Anyone who has used the Node.js bindings for [GraphicsMagick](https://github.com/aheckmann/gm) will find the API similarly fluent. -This module is powered by the blazingly fast [libvips](https://github.com/jcupitt/libvips) image processing library, originally created in 1989 at Birkbeck College and currently maintained by John Cupitt. +This module is powered by the blazingly fast [libvips](https://github.com/jcupitt/libvips) image processing library, originally created in 1989 at Birkbeck College and currently maintained by [John Cupitt](https://github.com/jcupitt). ## Installation @@ -89,13 +91,20 @@ sharp('input.jpg').resize(300, 200).toFile('output.jpg', function(err) { ``` ```javascript -sharp('input.jpg').rotate().resize(null, 200).progressive().toBuffer(function(err, outputBuffer, info) { +var transformer = sharp().resize(300, 200); +readableStream.pipe(transformer).pipe(writableStream); +// Read image data from readableStream, resize and write image data to writableStream +``` + +```javascript +var pipeline = sharp().rotate().resize(null, 200).progressive().toBuffer(function(err, outputBuffer, info) { if (err) { throw err; } // outputBuffer contains 200px high progressive JPEG image data, auto-rotated using EXIF Orientation tag // info.width and info.height contain the final pixel dimensions of the resized image }); +readableStream.pipe(pipeline); ``` ```javascript @@ -105,6 +114,15 @@ sharp('input.png').rotate(180).resize(300).sharpen().quality(90).webp().then(fun }); ``` +```javascript +http.createServer(function(request, response) { + response.writeHead(200, {'Content-Type': 'image/webp'}); + sharp('input.jpg').rotate().resize(200).webp().pipe(response); +}).listen(8000); +// Create HTTP server that always returns auto-rotated 'input.jpg', +// resized to 200 pixels wide, in WebP format +``` + ```javascript sharp(inputBuffer).resize(200, 300).bicubicInterpolation().embedWhite().toFile('output.tiff').then(function() { // output.tiff is a 200 pixels wide and 300 pixels high image containing a bicubic scaled @@ -132,14 +150,28 @@ sharp(inputBuffer).resize(200, 200).max().jpeg().then(function(outputBuffer, inf ## API -### sharp(input) +### Input methods -Constructor to which further methods are chained. `input` can be one of: +#### sharp([input]) + +Constructor to which further methods are chained. `input`, if present, can be one of: * Buffer containing JPEG, PNG or WebP image data, or * String containing the filename of an image, with most major formats supported. -### resize(width, [height]) +The object returned implements the [stream.Duplex](http://nodejs.org/api/stream.html#stream_class_stream_duplex) class. + +JPEG, PNG or WebP format image data can be streamed into the object when `input` is not provided. + +JPEG, PNG or WebP format image data can be streamed out from this object. + +#### sequentialRead() + +An advanced setting that switches the libvips access method to `VIPS_ACCESS_SEQUENTIAL`. This will reduce memory usage and can improve performance on some systems. + +### Image transformation options + +#### resize(width, [height]) Scale output to `width` x `height`. By default, the resized image is cropped to the exact size specified. @@ -147,25 +179,25 @@ Scale output to `width` x `height`. By default, the resized image is cropped to `height` is the Number of pixels high the resultant image should be. Use `null` or `undefined` to auto-scale the height to match the width. -### crop() +#### crop() Crop the resized image to the exact size specified, the default behaviour. -### max() +#### max() Preserving aspect ratio, resize the image to the maximum width or height specified. Both `width` and `height` must be provided via `resize` otherwise the behaviour will default to `crop`. -### embedWhite() +#### embedWhite() Embed the resized image on a white background of the exact size specified. -### embedBlack() +#### embedBlack() Embed the resized image on a black background of the exact size specified. -### rotate([angle]) +#### rotate([angle]) Rotate the output image by either an explicit angle or auto-orient based on the EXIF `Orientation` tag. @@ -173,49 +205,61 @@ Rotate the output image by either an explicit angle or auto-orient based on the Use this method without `angle` to determine the angle from EXIF data. Mirroring is currently unsupported. -### withoutEnlargement() +#### withoutEnlargement() Do not enlarge the output image if the input image width *or* height are already less than the required dimensions. This is equivalent to GraphicsMagick's `>` geometry option: "change the dimensions of the image only if its width or height exceeds the geometry specification". -### sharpen() +#### sharpen() Perform a mild sharpen of the resultant image. This typically reduces performance by 30%. -### bilinearInterpolation() +#### bilinearInterpolation() Use [bilinear interpolation](http://en.wikipedia.org/wiki/Bilinear_interpolation) for image resizing, the default (and fastest) interpolation if none is specified. -### bicubicInterpolation() +#### bicubicInterpolation() Use [bicubic interpolation](http://en.wikipedia.org/wiki/Bicubic_interpolation) for image resizing. This typically reduces performance by 5%. -### nohaloInterpolation() +#### nohaloInterpolation() Use [Nohalo interpolation](http://eprints.soton.ac.uk/268086/) for image resizing. This typically reduces performance by a factor of 2. -### progressive() +### Output options + +#### progressive() Use progressive (interlace) scan for JPEG and PNG output. This typically reduces compression performance by 30% but results in an image that can be rendered sooner when decompressed. -### quality(quality) +#### quality(quality) The output quality to use for lossy JPEG, WebP and TIFF output formats. The default quality is `80`. `quality` is a Number between 1 and 100. -### compressionLevel(compressionLevel) +#### compressionLevel(compressionLevel) An advanced setting for the _zlib_ compression level of the lossless PNG output format. The default level is `6`. `compressionLevel` is a Number between -1 and 9. -### sequentialRead() +#### jpeg() -An advanced setting that switches the libvips access method to `VIPS_ACCESS_SEQUENTIAL`. This will reduce memory usage and can improve performance on some systems. +Use JPEG format for the output image. -### toFile(filename, [callback]) +#### png() + +Use PNG format for the output image. + +#### webp() + +Use WebP format for the output image. + +### Output methods + +#### toFile(filename, [callback]) `filename` is a String containing the filename to write the image data to. The format is inferred from the extension, with JPEG, PNG, WebP and TIFF supported. @@ -226,9 +270,9 @@ An advanced setting that switches the libvips access method to `VIPS_ACCESS_SEQU A Promises/A+ promise is returned when `callback` is not provided. -### toBuffer([callback]) +#### toBuffer([callback]) -Write image data to a Buffer, the format of which will match the input image. JPEG, PNG and WebP are supported. +Write image data to a Buffer, the format of which will match the input image by default. JPEG, PNG and WebP are supported. `callback`, if present, gets three arguments `(err, buffer, info)` where: @@ -238,43 +282,9 @@ Write image data to a Buffer, the format of which will match the input image. JP A Promises/A+ promise is returned when `callback` is not provided. -### jpeg([callback]) +### Utility methods -Write JPEG image data to a Buffer. - -`callback`, if present, gets three arguments `(err, buffer, info)` where: - -* `err` is an error message, if any -* `buffer` is the resultant JPEG image data -* `info` contains the final resized image dimensions in its `width` and `height` properties - -A Promises/A+ promise is returned when `callback` is not provided. - -### png([callback]) - -Write PNG image data to a Buffer. - -`callback`, if present, gets three arguments `(err, buffer, info)` where: - -* `err` is an error message, if any -* `buffer` is the resultant PNG image data -* `info` contains the final resized image dimensions in its `width` and `height` properties - -A Promises/A+ promise is returned when `callback` is not provided. - -### webp([callback]) - -Write WebP image data to a Buffer. - -`callback`, if present, gets three arguments `(err, buffer, info)` where: - -* `err` is an error message, if any -* `buffer` is the resultant WebP image data -* `info` contains the final resized image dimensions in its `width` and `height` properties - -A Promises/A+ promise is returned when `callback` is not provided. - -### sharp.cache([limit]) +#### sharp.cache([limit]) If `limit` is provided, set the (soft) limit of _libvips_ working/cache memory to this value in MB. The default value is 100. diff --git a/index.js b/index.js index e54ec7d6..c60ca98c 100755 --- a/index.js +++ b/index.js @@ -1,6 +1,8 @@ /*jslint node: true */ 'use strict'; +var util = require('util'); +var stream = require('stream'); var Promise = require('bluebird'); var sharp = require('./build/Release/sharp'); @@ -8,6 +10,7 @@ var Sharp = function(input) { if (!(this instanceof Sharp)) { return new Sharp(input); } + stream.Duplex.call(this); this.options = { width: -1, height: -1, @@ -20,22 +23,54 @@ var Sharp = function(input) { sequentialRead: false, quality: 80, compressionLevel: 6, - output: '__jpeg' + streamIn: false, + streamOut: false, + output: '__input' }; if (typeof input === 'string') { + // input=file this.options.fileIn = input; - } else if (typeof input ==='object' && input instanceof Buffer) { + } else if (typeof input === 'object' && input instanceof Buffer) { + // input=buffer if (input.length > 0) { this.options.bufferIn = input; } else { throw new Error('Buffer is empty'); } } else { - throw new Error('Unsupported input ' + typeof input); + // input=stream + this.options.streamIn = true; } return this; }; module.exports = Sharp; +util.inherits(Sharp, stream.Duplex); + +/* + Handle incoming chunk on Writable Stream +*/ +Sharp.prototype._write = function(chunk, encoding, callback) { + if (this.options.streamIn) { + if (typeof chunk === 'object' || chunk instanceof Buffer) { + if (typeof this.options.bufferIn === 'undefined') { + // Create new Buffer + this.options.bufferIn = new Buffer(chunk.length); + chunk.copy(this.options.bufferIn); + } else { + // Append to existing Buffer + this.options.bufferIn = Buffer.concat( + [this.options.bufferIn, chunk], + this.options.bufferIn.length + chunk.length + ); + } + callback(); + } else { + callback(new Error('Non-Buffer data on Writable Stream')); + } + } else { + callback(new Error('Unexpected data on Writable Stream')); + } +}; Sharp.prototype.crop = function() { this.options.canvas = 'c'; @@ -181,55 +216,122 @@ Sharp.prototype.toFile = function(output, callback) { return Promise.reject(errOutputIsInput); } } else { - return this._sharp(output, callback); + this.options.output = output; + return this._sharp(callback); } } return this; }; -// Deprecated to make way for future stream support - remove in v0.6.0 -Sharp.prototype.write = require('util').deprecate( - Sharp.prototype.toFile, - '.write() is deprecated and will be removed in v0.6.0. Use .toFile() instead.' -); - Sharp.prototype.toBuffer = function(callback) { - return this._sharp('__input', callback); + return this._sharp(callback); }; -Sharp.prototype.jpeg = function(callback) { - return this._sharp('__jpeg', callback); +Sharp.prototype.jpeg = function() { + this.options.output = '__jpeg'; + if (arguments.length > 0) { + console.error('Use of the jpeg() method with a callback is deprecated in 0.6.x and will be removed in 0.7.x'); + console.error('Please add toFile(), toBuffer() or Stream methods e.g. pipe() for JPEG output'); + this._sharp(arguments); + } + return this; }; -Sharp.prototype.png = function(callback) { - return this._sharp('__png', callback); +Sharp.prototype.png = function() { + this.options.output = '__png'; + if (arguments.length > 0) { + console.error('Use of the png() method with a callback is deprecated in 0.6.x and will be removed in 0.7.x'); + console.error('Please add toFile(), toBuffer() or Stream methods e.g. pipe() for PNG output'); + this._sharp(arguments); + } + return this; }; -Sharp.prototype.webp = function(callback) { - return this._sharp('__webp', callback); +Sharp.prototype.webp = function() { + this.options.output = '__webp'; + if (arguments.length > 0) { + console.error('Use of the webp() method with a callback is deprecated in 0.6.x and will be removed in 0.7.x'); + console.error('Please add toFile(), toBuffer() or Stream methods e.g. pipe() for WebP output'); + this._sharp(arguments); + } + return this; +}; + +/* + Used by a Writable Stream to notify that it is ready for data +*/ +Sharp.prototype._read = function() { + if (!this.options.streamOut) { + this.options.streamOut = true; + this._sharp(); + } }; /* Invoke the C++ image processing pipeline - Supports callback and promise variants + Supports callback, stream and promise variants */ -Sharp.prototype._sharp = function(output, callback) { +Sharp.prototype._sharp = function(callback) { + var that = this; if (typeof callback === 'function') { - // I like callbacks - sharp.resize(this.options, output, callback); + // output=file/buffer + if (this.options.streamIn) { + // output=file/buffer, input=stream + this.on('finish', function() { + sharp.resize(that.options, callback); + }); + } else { + // output=file/buffer, input=file/buffer + sharp.resize(this.options, callback); + } + return this; + } else if (this.options.streamOut) { + // output=stream + if (this.options.streamIn) { + // output=stream, input=stream + this.on('finish', function() { + sharp.resize(that.options, function(err, data) { + if (err) throw err; + that.push(data); + that.push(null); + }); + }); + } else { + // output=stream, input=file/buffer + sharp.resize(this.options, function(err, data) { + if (err) throw err; + that.push(data); + that.push(null); + }); + } return this; } else { - // I like promises - var options = this.options; - return new Promise(function(resolve, reject) { - sharp.resize(options, output, function(err, data, info) { - if (err) { - reject(err); - } else { - resolve(data, info); - } + // output=promise + if (this.options.streamIn) { + // output=promise, input=stream + return new Promise(function(resolve, reject) { + that.on('finish', function() { + sharp.resize(that.options, function(err, data) { + if (err) { + reject(err); + } else { + resolve(data); + } + }); + }); }); - }); + } else { + // output=promise, input=file/buffer + return new Promise(function(resolve, reject) { + sharp.resize(that.options, function(err, data) { + if (err) { + reject(err); + } else { + resolve(data); + } + }); + }); + } } }; diff --git a/package.json b/package.json index 6a112def..40d1b5ab 100755 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "sharp", - "version": "0.5.3", + "version": "0.6.0", "author": "Lovell Fuller ", "contributors": [ "Pierre Inglebert ", @@ -30,7 +30,8 @@ "libvips", "vips", "fast", - "buffer" + "buffer", + "stream" ], "dependencies": { "nan": "^1.3.0", diff --git a/src/sharp.cc b/src/sharp.cc index a47c27c9..f274007a 100755 --- a/src/sharp.cc +++ b/src/sharp.cc @@ -14,7 +14,7 @@ struct resize_baton { std::string file_in; void* buffer_in; size_t buffer_in_len; - std::string file_out; + std::string output; void* buffer_out; size_t buffer_out_len; int width; @@ -386,43 +386,43 @@ class ResizeWorker : public NanAsyncWorker { // Output VipsImage *output = cached; - if (baton->file_out == "__jpeg" || (baton->file_out == "__input" && inputImageType == JPEG)) { + if (baton->output == "__jpeg" || (baton->output == "__input" && inputImageType == JPEG)) { // Write JPEG to buffer if (vips_jpegsave_buffer(output, &baton->buffer_out, &baton->buffer_out_len, "strip", TRUE, "Q", baton->quality, "optimize_coding", TRUE, "interlace", baton->progressive, NULL)) { return resize_error(baton, output); } - } else if (baton->file_out == "__png" || (baton->file_out == "__input" && inputImageType == PNG)) { + } else if (baton->output == "__png" || (baton->output == "__input" && inputImageType == PNG)) { // Write PNG to buffer if (vips_pngsave_buffer(output, &baton->buffer_out, &baton->buffer_out_len, "strip", TRUE, "compression", baton->compressionLevel, "interlace", baton->progressive, NULL)) { return resize_error(baton, output); } - } else if (baton->file_out == "__webp" || (baton->file_out == "__input" && inputImageType == WEBP)) { + } else if (baton->output == "__webp" || (baton->output == "__input" && inputImageType == WEBP)) { // Write WEBP to buffer if (vips_webpsave_buffer(output, &baton->buffer_out, &baton->buffer_out_len, "strip", TRUE, "Q", baton->quality, NULL)) { return resize_error(baton, output); } - } else if (is_jpeg(baton->file_out)) { + } else if (is_jpeg(baton->output)) { // Write JPEG to file - if (vips_jpegsave(output, baton->file_out.c_str(), "strip", TRUE, "Q", baton->quality, "optimize_coding", TRUE, "interlace", baton->progressive, NULL)) { + if (vips_jpegsave(output, baton->output.c_str(), "strip", TRUE, "Q", baton->quality, "optimize_coding", TRUE, "interlace", baton->progressive, NULL)) { return resize_error(baton, output); } - } else if (is_png(baton->file_out)) { + } else if (is_png(baton->output)) { // Write PNG to file - if (vips_pngsave(output, baton->file_out.c_str(), "strip", TRUE, "compression", baton->compressionLevel, "interlace", baton->progressive, NULL)) { + if (vips_pngsave(output, baton->output.c_str(), "strip", TRUE, "compression", baton->compressionLevel, "interlace", baton->progressive, NULL)) { return resize_error(baton, output); } - } else if (is_webp(baton->file_out)) { + } else if (is_webp(baton->output)) { // Write WEBP to file - if (vips_webpsave(output, baton->file_out.c_str(), "strip", TRUE, "Q", baton->quality, NULL)) { + if (vips_webpsave(output, baton->output.c_str(), "strip", TRUE, "Q", baton->quality, NULL)) { return resize_error(baton, output); } - } else if (is_tiff(baton->file_out)) { + } else if (is_tiff(baton->output)) { // Write TIFF to file - if (vips_tiffsave(output, baton->file_out.c_str(), "strip", TRUE, "compression", VIPS_FOREIGN_TIFF_COMPRESSION_JPEG, "Q", baton->quality, NULL)) { + if (vips_tiffsave(output, baton->output.c_str(), "strip", TRUE, "compression", VIPS_FOREIGN_TIFF_COMPRESSION_JPEG, "Q", baton->quality, NULL)) { return resize_error(baton, output); } } else { - (baton->err).append("Unsupported output " + baton->file_out); + (baton->err).append("Unsupported output " + baton->output); } g_object_unref(output); @@ -506,10 +506,10 @@ NAN_METHOD(resize) { baton->compressionLevel = options->Get(NanNew("compressionLevel"))->Int32Value(); baton->angle = options->Get(NanNew("angle"))->Int32Value(); // Output filename or __format for Buffer - baton->file_out = *String::Utf8Value(args[1]->ToString()); + baton->output = *String::Utf8Value(options->Get(NanNew("output"))->ToString()); // Join queue for worker thread - NanCallback *callback = new NanCallback(args[2].As()); + NanCallback *callback = new NanCallback(args[1].As()); NanAsyncQueueWorker(new ResizeWorker(callback, baton)); // Increment queue length diff --git a/tests/perf.js b/tests/perf.js index 160208a6..c53c9e70 100755 --- a/tests/perf.js +++ b/tests/perf.js @@ -142,6 +142,17 @@ async.series({ } }); } + }).add("sharp-stream-stream", { + defer: true, + fn: function(deferred) { + var readable = fs.createReadStream(inputJpg); + var writable = fs.createWriteStream(outputJpg); + writable.on('finish', function() { + deferred.resolve(); + }); + var pipeline = sharp().resize(width, height); + readable.pipe(pipeline).pipe(writable); + } }).add("sharp-file-buffer", { defer: true, fn: function(deferred) { diff --git a/tests/unit.js b/tests/unit.js index 5c125366..7bd99cbe 100755 --- a/tests/unit.js +++ b/tests/unit.js @@ -3,8 +3,8 @@ 'use strict'; var sharp = require("../index"); +var fs = require("fs"); var path = require("path"); -var imagemagick = require("imagemagick"); var assert = require("assert"); var async = require("async"); @@ -21,79 +21,61 @@ var inputJpgWithExif = path.join(fixturesPath, "Landscape_8.jpg"); // https://gi async.series([ // Resize with exact crop function(done) { - sharp(inputJpg).resize(320, 240).toFile(outputJpg, function(err, info) { + sharp(inputJpg).resize(320, 240).toBuffer(function(err, data, info) { if (err) throw err; + assert.strictEqual(true, data.length > 0); assert.strictEqual(320, info.width); assert.strictEqual(240, info.height); - imagemagick.identify(outputJpg, function(err, features) { - if (err) throw err; - assert.strictEqual(320, features.width); - assert.strictEqual(240, features.height); - done(); - }); + done(); }); }, // Resize to fixed width function(done) { - sharp(inputJpg).resize(320).toFile(outputJpg, function(err, info) { + sharp(inputJpg).resize(320).toBuffer(function(err, data, info) { if (err) throw err; + assert.strictEqual(true, data.length > 0); assert.strictEqual(320, info.width); assert.strictEqual(261, info.height); - imagemagick.identify(outputJpg, function(err, features) { - if (err) throw err; - assert.strictEqual(320, features.width); - assert.strictEqual(261, features.height); - done(); - }); + done(); }); }, // Resize to fixed height function(done) { - sharp(inputJpg).resize(null, 320).toFile(outputJpg, function(err, info) { + sharp(inputJpg).resize(null, 320).toBuffer(function(err, data, info) { if (err) throw err; + assert.strictEqual(true, data.length > 0); assert.strictEqual(391, info.width); assert.strictEqual(320, info.height); - imagemagick.identify(outputJpg, function(err, features) { - if (err) throw err; - assert.strictEqual(391, features.width); - assert.strictEqual(320, features.height); - done(); - }); + done(); }); }, // Identity transform function(done) { - sharp(inputJpg).toFile(outputJpg, function(err) { + sharp(inputJpg).toBuffer(function(err, data, info) { if (err) throw err; - imagemagick.identify(outputJpg, function(err, features) { - if (err) throw err; - assert.strictEqual(2725, features.width); - assert.strictEqual(2225, features.height); - done(); - }); + assert.strictEqual(true, data.length > 0); + assert.strictEqual(2725, info.width); + assert.strictEqual(2225, info.height); + done(); }); }, // Upscale function(done) { - sharp(inputJpg).resize(3000).toFile(outputJpg, function(err, info) { + sharp(inputJpg).resize(3000).toBuffer(function(err, data, info) { if (err) throw err; + assert.strictEqual(true, data.length > 0); assert.strictEqual(3000, info.width); assert.strictEqual(2449, info.height); - imagemagick.identify(outputJpg, function(err, features) { - if (err) throw err; - assert.strictEqual(3000, features.width); - assert.strictEqual(2449, features.height); - done(); - }); + done(); }); }, // Quality function(done) { - sharp(inputJpg).resize(320, 240).quality(70).jpeg(function(err, buffer70) { + sharp(inputJpg).resize(320, 240).quality(70).toBuffer(function(err, buffer70) { if (err) throw err; - sharp(inputJpg).resize(320, 240).jpeg(function(err, buffer80) { + sharp(inputJpg).resize(320, 240).toBuffer(function(err, buffer80) { if (err) throw err; - sharp(inputJpg).resize(320, 240).quality(90).jpeg(function(err, buffer90) { + sharp(inputJpg).resize(320, 240).quality(90).toBuffer(function(err, buffer90) { assert(buffer70.length < buffer80.length); assert(buffer80.length < buffer90.length); done(); @@ -103,67 +85,51 @@ async.series([ }, // TIFF with dimensions known to cause rounding errors function(done) { - sharp(inputTiff).resize(240, 320).embedBlack().toFile(outputJpg, function(err) { + sharp(inputTiff).resize(240, 320).embedBlack().jpeg().toBuffer(function(err, data, info) { if (err) throw err; - imagemagick.identify(outputJpg, function(err, features) { - if (err) throw err; - assert.strictEqual(240, features.width); - assert.strictEqual(320, features.height); - done(); - }); + assert.strictEqual(true, data.length > 0); + assert.strictEqual(240, info.width); + assert.strictEqual(320, info.height); + done(); }); }, function(done) { - sharp(inputTiff).resize(240, 320).toFile(outputJpg, function(err) { + sharp(inputTiff).resize(240, 320).jpeg().toBuffer(function(err, data, info) { if (err) throw err; - imagemagick.identify(outputJpg, function(err, features) { - if (err) throw err; - assert.strictEqual(240, features.width); - assert.strictEqual(320, features.height); - done(); - }); + assert.strictEqual(true, data.length > 0); + assert.strictEqual(240, info.width); + assert.strictEqual(320, info.height); + done(); }); }, // Resize to max width or height considering ratio (landscape) function(done) { - sharp(inputJpg).resize(320, 320).max().toFile(outputJpg, function(err, info) { + sharp(inputJpg).resize(320, 320).max().toBuffer(function(err, data, info) { if (err) throw err; + assert.strictEqual(true, data.length > 0); assert.strictEqual(320, info.width); assert.strictEqual(261, info.height); - imagemagick.identify(outputJpg, function(err, features) { - if (err) throw err; - assert.strictEqual(320, features.width); - assert.strictEqual(261, features.height); - done(); - }); + done(); }); }, // Resize to max width or height considering ratio (portrait) function(done) { - sharp(inputTiff).resize(320, 320).max().toFile(outputJpg, function(err, info) { + sharp(inputTiff).resize(320, 320).max().jpeg().toBuffer(function(err, data, info) { if (err) throw err; + assert.strictEqual(true, data.length > 0); assert.strictEqual(243, info.width); assert.strictEqual(320, info.height); - imagemagick.identify(outputJpg, function(err, features) { - if (err) throw err; - assert.strictEqual(243, features.width); - assert.strictEqual(320, features.height); - done(); - }); + done(); }); }, // Attempt to resize to max but only provide one dimension, so should default to crop function(done) { - sharp(inputJpg).resize(320).max().toFile(outputJpg, function(err, info) { + sharp(inputJpg).resize(320).max().toBuffer(function(err, data, info) { if (err) throw err; + assert.strictEqual(true, data.length > 0); assert.strictEqual(320, info.width); assert.strictEqual(261, info.height); - imagemagick.identify(outputJpg, function(err, features) { - if (err) throw err; - assert.strictEqual(320, features.width); - assert.strictEqual(261, features.height); - done(); - }); + done(); }); }, // Attempt to output to input, should fail @@ -175,58 +141,42 @@ async.series([ }, // Rotate by 90 degrees, respecting output input size function(done) { - sharp(inputJpg).rotate(90).resize(320, 240).toFile(outputJpg, function(err, info) { + sharp(inputJpg).rotate(90).resize(320, 240).toBuffer(function(err, data, info) { if (err) throw err; + assert.strictEqual(true, data.length > 0); assert.strictEqual(320, info.width); assert.strictEqual(240, info.height); - imagemagick.identify(outputJpg, function(err, features) { - if (err) throw err; - assert.strictEqual(320, features.width); - assert.strictEqual(240, features.height); - done(); - }); + done(); }); }, // Input image has Orientation EXIF tag but do not rotate output function(done) { - sharp(inputJpgWithExif).resize(320).toFile(outputJpg, function(err, info) { + sharp(inputJpgWithExif).resize(320).toBuffer(function(err, data, info) { if (err) throw err; + assert.strictEqual(true, data.length > 0); assert.strictEqual(320, info.width); assert.strictEqual(426, info.height); - imagemagick.identify(outputJpg, function(err, features) { - if (err) throw err; - assert.strictEqual(320, features.width); - assert.strictEqual(426, features.height); - done(); - }); + done(); }); }, // Input image has Orientation EXIF tag value of 8 (270 degrees), auto-rotate function(done) { - sharp(inputJpgWithExif).rotate().resize(320).toFile(outputJpg, function(err, info) { + sharp(inputJpgWithExif).rotate().resize(320).toBuffer(function(err, data, info) { if (err) throw err; + assert.strictEqual(true, data.length > 0); assert.strictEqual(320, info.width); assert.strictEqual(240, info.height); - imagemagick.identify(outputJpg, function(err, features) { - if (err) throw err; - assert.strictEqual(320, features.width); - assert.strictEqual(240, features.height); - done(); - }); + done(); }); }, // Attempt to auto-rotate using image that has no EXIF function(done) { - sharp(inputJpg).rotate().resize(320).toFile(outputJpg, function(err, info) { + sharp(inputJpg).rotate().resize(320).toBuffer(function(err, data, info) { if (err) throw err; + assert.strictEqual(true, data.length > 0); assert.strictEqual(320, info.width); assert.strictEqual(261, info.height); - imagemagick.identify(outputJpg, function(err, features) { - if (err) throw err; - assert.strictEqual(320, features.width); - assert.strictEqual(261, features.height); - done(); - }); + done(); }); }, // Rotate to an invalid angle, should fail @@ -241,40 +191,32 @@ async.series([ }, // Do not enlarge the output if the input width is already less than the output width function(done) { - sharp(inputJpg).resize(2800).withoutEnlargement().toFile(outputJpg, function(err, info) { + sharp(inputJpg).resize(2800).withoutEnlargement().toBuffer(function(err, data, info) { if (err) throw err; + assert.strictEqual(true, data.length > 0); assert.strictEqual(2725, info.width); assert.strictEqual(2225, info.height); - imagemagick.identify(outputJpg, function(err, features) { - if (err) throw err; - assert.strictEqual(2725, features.width); - assert.strictEqual(2225, features.height); - done(); - }); + done(); }); }, // Do not enlarge the output if the input height is already less than the output height function(done) { - sharp(inputJpg).resize(null, 2300).withoutEnlargement().toFile(outputJpg, function(err, info) { + sharp(inputJpg).resize(null, 2300).withoutEnlargement().toBuffer(function(err, data, info) { if (err) throw err; + assert.strictEqual(true, data.length > 0); assert.strictEqual(2725, info.width); assert.strictEqual(2225, info.height); - imagemagick.identify(outputJpg, function(err, features) { - if (err) throw err; - assert.strictEqual(2725, features.width); - assert.strictEqual(2225, features.height); - done(); - }); + done(); }); }, // Promises/A+ function(done) { - sharp(inputJpg).resize(320, 240).toFile(outputJpg).then(function(info) { - assert.strictEqual(320, info.width); - assert.strictEqual(240, info.height); - imagemagick.identify(outputJpg, function(err, features) { - assert.strictEqual(320, features.width); - assert.strictEqual(240, features.height); + sharp(inputJpg).resize(320, 240).toBuffer().then(function(data) { + sharp(data).toBuffer(function(err, data, info) { + if (err) throw err; + assert.strictEqual(true, data.length > 0); + assert.strictEqual(320, info.width); + assert.strictEqual(240, info.height); done(); }); }).catch(function(err) { @@ -293,44 +235,109 @@ async.series([ }, // Check colour space conversion occurs from TIFF to WebP (this used to segfault) function(done) { - sharp(inputTiff).webp().then(function() { + sharp(inputTiff).webp().toBuffer().then(function() { done(); }); }, // Interpolation: bilinear function(done) { - sharp(inputJpg).resize(320, 240).bilinearInterpolation().toFile(outputJpg, function(err) { + sharp(inputJpg).resize(320, 240).bilinearInterpolation().toBuffer(function(err, data, info) { if (err) throw err; - imagemagick.identify(outputJpg, function(err, features) { - if (err) throw err; - assert.strictEqual(320, features.width); - assert.strictEqual(240, features.height); - done(); - }); + assert.strictEqual(true, data.length > 0); + assert.strictEqual(320, info.width); + assert.strictEqual(240, info.height); + done(); }); }, // Interpolation: bicubic function(done) { - sharp(inputJpg).resize(320, 240).bicubicInterpolation().toFile(outputJpg, function(err) { + sharp(inputJpg).resize(320, 240).bicubicInterpolation().toBuffer(function(err, data, info) { if (err) throw err; - imagemagick.identify(outputJpg, function(err, features) { - if (err) throw err; - assert.strictEqual(320, features.width); - assert.strictEqual(240, features.height); - done(); - }); + assert.strictEqual(true, data.length > 0); + assert.strictEqual(320, info.width); + assert.strictEqual(240, info.height); + done(); }); }, // Interpolation: nohalo function(done) { - sharp(inputJpg).resize(320, 240).nohaloInterpolation().toFile(outputJpg, function(err) { + sharp(inputJpg).resize(320, 240).nohaloInterpolation().toBuffer(function(err, data, info) { if (err) throw err; - imagemagick.identify(outputJpg, function(err, features) { + assert.strictEqual(true, data.length > 0); + assert.strictEqual(320, info.width); + assert.strictEqual(240, info.height); + done(); + }); + }, + // File-Stream + function(done) { + var writable = fs.createWriteStream(outputJpg); + writable.on('finish', function() { + sharp(outputJpg).toBuffer(function(err, data, info) { if (err) throw err; - assert.strictEqual(320, features.width); - assert.strictEqual(240, features.height); + assert.strictEqual(true, data.length > 0); + assert.strictEqual(320, info.width); + assert.strictEqual(240, info.height); + fs.unlinkSync(outputJpg); done(); }); }); + sharp(inputJpg).resize(320, 240).pipe(writable); }, + // Buffer-Stream + function(done) { + var inputJpgBuffer = fs.readFileSync(inputJpg); + var writable = fs.createWriteStream(outputJpg); + writable.on('finish', function() { + sharp(outputJpg).toBuffer(function(err, data, info) { + if (err) throw err; + assert.strictEqual(true, data.length > 0); + assert.strictEqual(320, info.width); + assert.strictEqual(240, info.height); + fs.unlinkSync(outputJpg); + done(); + }); + }); + sharp(inputJpgBuffer).resize(320, 240).pipe(writable); + }, + // Stream-File + function(done) { + var readable = fs.createReadStream(inputJpg); + var pipeline = sharp().resize(320, 240).toFile(outputJpg, function(err, info) { + if (err) throw err; + assert.strictEqual(320, info.width); + assert.strictEqual(240, info.height); + fs.unlinkSync(outputJpg); + done(); + }); + readable.pipe(pipeline); + }, + // Stream-Buffer + function(done) { + var readable = fs.createReadStream(inputJpg); + var pipeline = sharp().resize(320, 240).toBuffer(function(err, data, info) { + if (err) throw err; + assert.strictEqual(320, info.width); + assert.strictEqual(240, info.height); + done(); + }); + readable.pipe(pipeline); + }, + // Stream-Stream + function(done) { + var readable = fs.createReadStream(inputJpg); + var writable = fs.createWriteStream(outputJpg); + writable.on('finish', function() { + sharp(outputJpg).toBuffer(function(err, data, info) { + if (err) throw err; + assert.strictEqual(true, data.length > 0); + assert.strictEqual(320, info.width); + assert.strictEqual(240, info.height); + fs.unlinkSync(outputJpg); + done(); + }); + }); + var pipeline = sharp().resize(320, 240); + readable.pipe(pipeline).pipe(writable) + } ]);