Compare commits
132 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c4a278ec9c | ||
|
|
658a541f49 | ||
|
|
01435977de | ||
|
|
36ac8828f2 | ||
|
|
9c83d98bbb | ||
|
|
dee9ca3ec2 | ||
|
|
d375327d20 | ||
|
|
09244192e9 | ||
|
|
de333eb02d | ||
|
|
8b50f15a44 | ||
|
|
f853fa3e23 | ||
|
|
d26f6b3b89 | ||
|
|
022a2b1ade | ||
|
|
4f1ac5717e | ||
|
|
d303703dc5 | ||
|
|
642e5687b6 | ||
|
|
2ec845b083 | ||
|
|
c40cd1aa50 | ||
|
|
804162c69a | ||
|
|
08b2a647d0 | ||
|
|
3a058c0c27 | ||
|
|
b8885c1faa | ||
|
|
321e0f2bfe | ||
|
|
cff8b45420 | ||
|
|
6ac47c1ef8 | ||
|
|
86490bedfb | ||
|
|
1091be374e | ||
|
|
36be0453dd | ||
|
|
e2c53b59ce | ||
|
|
f19b6c48ca | ||
|
|
d2a2654ace | ||
|
|
8832ae0bf9 | ||
|
|
ef8db1eebf | ||
|
|
c792a047b1 | ||
|
|
64f7f1d662 | ||
|
|
c886eaa6b0 | ||
|
|
b50fb53f27 | ||
|
|
75d72cfded | ||
|
|
21b0d8c7f7 | ||
|
|
fa8f06f07d | ||
|
|
e07a105b7c | ||
|
|
4f72dcbf54 | ||
|
|
b77877c83d | ||
|
|
8fd3520257 | ||
|
|
f15e64039c | ||
|
|
3ffe2ba17f | ||
|
|
33782d3c83 | ||
|
|
783826aa26 | ||
|
|
c2ef16eac2 | ||
|
|
e999fb6e30 | ||
|
|
d1fc0591a5 | ||
|
|
fb1c9cf3d3 | ||
|
|
21ba1dfc26 | ||
|
|
dacd62428e | ||
|
|
1e52c2dbe6 | ||
|
|
8926ebc56c | ||
|
|
9da87ce868 | ||
|
|
46cc45c186 | ||
|
|
54f2243386 | ||
|
|
8ac33aad69 | ||
|
|
6fc62d39c9 | ||
|
|
a0655806de | ||
|
|
3614d14f83 | ||
|
|
f6fd45cc90 | ||
|
|
be39297f3b | ||
|
|
dce36e0074 | ||
|
|
ba034a8164 | ||
|
|
3dfc7bea3a | ||
|
|
f72435c750 | ||
|
|
3810f642d3 | ||
|
|
ae968142ee | ||
|
|
ccb7887cb9 | ||
|
|
f1ad1216ca | ||
|
|
ce6813329b | ||
|
|
7ad7193b1e | ||
|
|
bd96a49de6 | ||
|
|
81c710eaa3 | ||
|
|
711f0fefb6 | ||
|
|
33ca86e4f2 | ||
|
|
9b5229f2dd | ||
|
|
5781a23a4d | ||
|
|
2d1e6f2644 | ||
|
|
5240eeb518 | ||
|
|
125ee836fe | ||
|
|
3ca2f009f4 | ||
|
|
a900c28f7c | ||
|
|
77bbbb9715 | ||
|
|
88753a6333 | ||
|
|
bcd82f4893 | ||
|
|
749dc61f85 | ||
|
|
c7ccf6801d | ||
|
|
1565522ecc | ||
|
|
a44df2f533 | ||
|
|
317510746f | ||
|
|
ef54e327b7 | ||
|
|
d8d0158774 | ||
|
|
4d75f27a25 | ||
|
|
f89e9d726d | ||
|
|
5194b37460 | ||
|
|
55ea432711 | ||
|
|
ab7408c96f | ||
|
|
1f7e80e581 | ||
|
|
0e91ca90d6 | ||
|
|
8f41fed9c2 | ||
|
|
96dd40cee1 | ||
|
|
62767d072b | ||
|
|
33880ce19e | ||
|
|
988176846d | ||
|
|
657d436a0f | ||
|
|
e5549e3063 | ||
|
|
0b2fb967b8 | ||
|
|
f57478c1aa | ||
|
|
e5a5e2ca7e | ||
|
|
797d503a99 | ||
|
|
512a281986 | ||
|
|
37c5ca7166 | ||
|
|
cda700ef73 | ||
|
|
d32901da8d | ||
|
|
83ebe12061 | ||
|
|
fe34548bad | ||
|
|
855945bef2 | ||
|
|
8421e3aa5f | ||
|
|
c93f79daa7 | ||
|
|
35c53f78c8 | ||
|
|
c158d51f8b | ||
|
|
8e9a8dfede | ||
|
|
67dc694cfb | ||
|
|
74704a132c | ||
|
|
b86674f91f | ||
|
|
5dab3c8482 | ||
|
|
a190ae6b08 | ||
|
|
464fb1726d |
2
.gitignore
vendored
@@ -2,7 +2,7 @@ build
|
|||||||
node_modules
|
node_modules
|
||||||
coverage
|
coverage
|
||||||
test/bench/node_modules
|
test/bench/node_modules
|
||||||
test/fixtures/output.*
|
test/fixtures/output*
|
||||||
test/leak/libvips.supp
|
test/leak/libvips.supp
|
||||||
|
|
||||||
# Mac OS X
|
# Mac OS X
|
||||||
|
|||||||
@@ -1,7 +1,10 @@
|
|||||||
{
|
{
|
||||||
"strict": true,
|
"strict": true,
|
||||||
"node": true,
|
"node": true,
|
||||||
|
"maxparams": 4,
|
||||||
|
"maxcomplexity": 13,
|
||||||
"globals": {
|
"globals": {
|
||||||
|
"before": true,
|
||||||
"describe": true,
|
"describe": true,
|
||||||
"it": true
|
"it": true
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,3 +6,5 @@ coverage
|
|||||||
.gitignore
|
.gitignore
|
||||||
test
|
test
|
||||||
.travis.yml
|
.travis.yml
|
||||||
|
appveyor.yml
|
||||||
|
mkdocs.yml
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
language: node_js
|
language: node_js
|
||||||
node_js:
|
node_js:
|
||||||
- "0.10"
|
- "0.10"
|
||||||
- "0.11"
|
- "0.12"
|
||||||
|
- "iojs-v1"
|
||||||
|
- "iojs-v2"
|
||||||
before_install:
|
before_install:
|
||||||
- curl -s https://raw.githubusercontent.com/lovell/sharp/master/preinstall.sh | sudo bash -
|
- curl -s https://raw.githubusercontent.com/lovell/sharp/master/preinstall.sh | sudo bash -
|
||||||
after_success:
|
after_success:
|
||||||
|
|||||||
90
CONTRIBUTING.md
Normal file
@@ -0,0 +1,90 @@
|
|||||||
|
# Contributing to sharp
|
||||||
|
|
||||||
|
Hello, thank you for your interest in helping!
|
||||||
|
|
||||||
|
## Submit a new bug report
|
||||||
|
|
||||||
|
Please create a [new issue](https://github.com/lovell/sharp/issues/new) containing the steps to reproduce the problem.
|
||||||
|
|
||||||
|
New bugs are assigned a `triage` label whilst under investigation.
|
||||||
|
|
||||||
|
If you're having problems with `npm install sharp`, please include the output of the following commands, perhaps as a [gist](https://gist.github.com/):
|
||||||
|
|
||||||
|
```sh
|
||||||
|
vips -v
|
||||||
|
pkg-config --print-provides vips
|
||||||
|
npm install --verbose sharp
|
||||||
|
```
|
||||||
|
|
||||||
|
## Submit a new feature request
|
||||||
|
|
||||||
|
If a [similar request](https://github.com/lovell/sharp/labels/enhancement) exists, it's probably fastest to add a comment to it about your requirement.
|
||||||
|
|
||||||
|
Implementation is usually straightforward if _libvips_ [already supports](http://www.vips.ecs.soton.ac.uk/supported/current/doc/html/libvips/ch03.html) the feature you need.
|
||||||
|
|
||||||
|
## Submit a Pull Request to fix a bug
|
||||||
|
|
||||||
|
Thank you! To prevent the problem occurring again, please add unit tests that would have failed.
|
||||||
|
|
||||||
|
Please select the `master` branch as the destination for your Pull Request so your fix can be included in the next minor release.
|
||||||
|
|
||||||
|
Please squash your changes into a single commit using a command like `git rebase -i upstream/master`.
|
||||||
|
|
||||||
|
To test C++ changes, you can compile the module using `npm install` and then run the tests using `npm test`.
|
||||||
|
|
||||||
|
## Submit a Pull Request with a new feature
|
||||||
|
|
||||||
|
Please add JavaScript [unit tests](https://github.com/lovell/sharp/tree/master/test/unit) to cover your new feature.
|
||||||
|
A test coverage report for the JavaScript code is generated in the `coverage/lcov-report` directory.
|
||||||
|
|
||||||
|
Where possible, the functional tests use gradient-based perceptual hashes
|
||||||
|
based on [dHash](http://www.hackerfactor.com/blog/index.php?/archives/529-Kind-of-Like-That.html)
|
||||||
|
to compare expected vs actual images.
|
||||||
|
|
||||||
|
You deserve to add your details to the [list of contributors](https://github.com/lovell/sharp/blob/master/package.json#L5).
|
||||||
|
|
||||||
|
Any change that modifies the existing public API should be added to the relevant work-in-progress branch for inclusion in the next major release.
|
||||||
|
|
||||||
|
| Release | WIP branch |
|
||||||
|
| ------: | :--------- |
|
||||||
|
| v0.11.0 | knife |
|
||||||
|
| v0.12.0 | look |
|
||||||
|
| v0.13.0 | mind |
|
||||||
|
|
||||||
|
Please squash your changes into a single commit using a command like `git rebase -i upstream/<wip-branch>`.
|
||||||
|
|
||||||
|
### Add a new public method
|
||||||
|
|
||||||
|
The API tries to be as fluent as possible. Image processing concepts follow the naming conventions from _libvips_ and, to a lesser extent, _ImageMagick_.
|
||||||
|
|
||||||
|
Most methods have optional parameters and assume sensible defaults. Methods with mandatory parameters often have names like `doSomethingWith(X)`.
|
||||||
|
|
||||||
|
Please ensure backwards compatibility where possible. Methods to modify previously default behaviour often have names like `withoutOptionY()` or `withExtraZ()`.
|
||||||
|
|
||||||
|
Feel free to create a [new issue](https://github.com/lovell/sharp/issues/new) to gather feedback on a potential API change.
|
||||||
|
|
||||||
|
### Remove an existing public method
|
||||||
|
|
||||||
|
A method to be removed should be deprecated in the next major version then removed in the following major version.
|
||||||
|
|
||||||
|
By way of example, the [bilinearInterpolation method](https://github.com/lovell/sharp/blob/v0.6.0/index.js#L155) present in v0.5.0 was deprecated in v0.6.0 and removed in v0.7.0.
|
||||||
|
|
||||||
|
## Run the tests
|
||||||
|
|
||||||
|
### Functional tests and static code analysis
|
||||||
|
|
||||||
|
```sh
|
||||||
|
npm test
|
||||||
|
```
|
||||||
|
|
||||||
|
### Memory leak tests
|
||||||
|
|
||||||
|
Requires [Valgrind](http://valgrind.org/).
|
||||||
|
|
||||||
|
```sh
|
||||||
|
npm run test-leak
|
||||||
|
```
|
||||||
|
|
||||||
|
## Finally
|
||||||
|
|
||||||
|
Please feel free to ask any questions via a [new issue](https://github.com/lovell/sharp/issues/new) or contact me by [e-mail](https://github.com/lovell/sharp/blob/master/package.json#L4).
|
||||||
620
README.md
Executable file → Normal file
@@ -1,622 +1,30 @@
|
|||||||
# sharp
|
# sharp
|
||||||
|
|
||||||
* [Installation](https://github.com/lovell/sharp#installation)
|
The typical use case for this high speed Node.js module
|
||||||
* [Usage examples](https://github.com/lovell/sharp#usage-examples)
|
is to convert large images of many formats to
|
||||||
* [API](https://github.com/lovell/sharp#api)
|
smaller, web-friendly JPEG, PNG and WebP images of varying dimensions.
|
||||||
* [Testing](https://github.com/lovell/sharp#testing)
|
|
||||||
* [Performance](https://github.com/lovell/sharp#performance)
|
|
||||||
* [Thanks](https://github.com/lovell/sharp#thanks)
|
|
||||||
* [Licence](https://github.com/lovell/sharp#licence)
|
|
||||||
|
|
||||||
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.
|
|
||||||
|
|
||||||
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.
|
|
||||||
Colour spaces, embedded ICC profiles and alpha transparency channels are all handled correctly.
|
|
||||||
|
|
||||||
Only small regions of uncompressed image data are held in memory and processed at a time, taking full advantage of multiple CPU cores and L1/L2/L3 cache. Resizing an image is typically 4x faster than using the quickest ImageMagick and GraphicsMagick settings.
|
|
||||||
|
|
||||||
Huffman tables are optimised when generating JPEG output images without having to use separate command line tools like [jpegoptim](https://github.com/tjko/jpegoptim) and [jpegtran](http://jpegclub.org/jpegtran/). PNG filtering can be disabled, which for diagrams and line art often produces the same result as [pngcrush](http://pmt.sourceforge.net/pngcrush/).
|
|
||||||
|
|
||||||
Everything remains non-blocking thanks to _libuv_, no child processes are spawned and Promises/A+ are supported.
|
|
||||||
|
|
||||||
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](https://github.com/jcupitt).
|
|
||||||
|
|
||||||
## Installation
|
|
||||||
|
|
||||||
npm install sharp
|
|
||||||
|
|
||||||
### Prerequisites
|
|
||||||
|
|
||||||
* Node.js v0.10+
|
|
||||||
* [libvips](https://github.com/jcupitt/libvips) v7.40.0+ (7.42.0+ recommended)
|
|
||||||
|
|
||||||
To install the most suitable version of libvips on the following Operating Systems:
|
|
||||||
|
|
||||||
* Mac OS
|
|
||||||
* Homebrew
|
|
||||||
* MacPorts
|
|
||||||
* Debian Linux
|
|
||||||
* Debian 7, 8
|
|
||||||
* Ubuntu 12.04, 14.04, 14.10, 15.04
|
|
||||||
* Mint 13, 17
|
|
||||||
* Red Hat Linux
|
|
||||||
* RHEL/Centos/Scientific 6, 7
|
|
||||||
* Fedora 21, 22
|
|
||||||
* Amazon Linux 2014.09
|
|
||||||
|
|
||||||
run the following as a user with `sudo` access:
|
|
||||||
|
|
||||||
curl -s https://raw.githubusercontent.com/lovell/sharp/master/preinstall.sh | sudo bash -
|
|
||||||
|
|
||||||
or run the following as `root`:
|
|
||||||
|
|
||||||
curl -s https://raw.githubusercontent.com/lovell/sharp/master/preinstall.sh | bash -
|
|
||||||
|
|
||||||
The [preinstall.sh](https://github.com/lovell/sharp/blob/master/preinstall.sh) script requires `curl` and `pkg-config`.
|
|
||||||
|
|
||||||
### Mac OS tips
|
|
||||||
|
|
||||||
Manual install via homebrew:
|
|
||||||
|
|
||||||
brew install homebrew/science/vips --with-webp --with-graphicsmagick
|
|
||||||
|
|
||||||
A missing or incorrectly configured _Xcode Command Line Tools_ installation [can lead](https://github.com/lovell/sharp/issues/80) to a `library not found for -ljpeg` error. If so, please try:
|
|
||||||
|
|
||||||
xcode-select --install
|
|
||||||
|
|
||||||
The _gettext_ dependency of _libvips_ [can lead](https://github.com/lovell/sharp/issues/9) to a `library not found for -lintl` error. If so, please try:
|
|
||||||
|
|
||||||
brew link gettext --force
|
|
||||||
|
|
||||||
### Heroku
|
|
||||||
|
|
||||||
[Alessandro Tagliapietra](https://github.com/alex88) maintains an [Heroku buildpack for libvips](https://github.com/alex88/heroku-buildpack-vips) and its dependencies.
|
|
||||||
|
|
||||||
### Docker
|
|
||||||
|
|
||||||
[Marc Bachmann](https://github.com/marcbachmann) maintains a [Dockerfile for libvips](https://github.com/marcbachmann/dockerfile-libvips).
|
|
||||||
|
|
||||||
docker pull marcbachmann/libvips
|
|
||||||
|
|
||||||
### gulp.js
|
|
||||||
|
|
||||||
[Eugeny Vlasenko](https://github.com/mahnunchik) maintains [gulp-responsive](https://www.npmjs.org/package/gulp-responsive) and [Mohammad Prabowo](https://github.com/rizalp) maintains [gulp-sharp](https://www.npmjs.org/package/gulp-sharp).
|
|
||||||
|
|
||||||
## Usage examples
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
var sharp = require('sharp');
|
|
||||||
```
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
sharp('input.jpg').resize(300, 200).toFile('output.jpg', function(err) {
|
|
||||||
if (err) {
|
|
||||||
throw err;
|
|
||||||
}
|
|
||||||
// output.jpg is a 300 pixels wide and 200 pixels high image
|
|
||||||
// containing a scaled and cropped version of input.jpg
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
var transformer = sharp().resize(300, 200).crop(sharp.gravity.north);
|
|
||||||
readableStream.pipe(transformer).pipe(writableStream);
|
|
||||||
// Read image data from readableStream, resize and write image data to writableStream
|
|
||||||
```
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
var image = sharp(inputJpg);
|
|
||||||
image.metadata(function(err, metadata) {
|
|
||||||
image.resize(metadata.width / 2).webp().toBuffer(function(err, outputBuffer, info) {
|
|
||||||
// outputBuffer contains a WebP image half the width and height of the original JPEG
|
|
||||||
});
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
```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 dimensions of the resized image
|
|
||||||
});
|
|
||||||
readableStream.pipe(pipeline);
|
|
||||||
```
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
sharp('input.png')
|
|
||||||
.rotate(180)
|
|
||||||
.resize(300)
|
|
||||||
.flatten()
|
|
||||||
.background('#ff6600')
|
|
||||||
.sharpen()
|
|
||||||
.withMetadata()
|
|
||||||
.quality(90)
|
|
||||||
.webp()
|
|
||||||
.toBuffer()
|
|
||||||
.then(function(outputBuffer) {
|
|
||||||
// outputBuffer contains upside down, 300px wide, alpha channel flattened
|
|
||||||
// onto orange background, sharpened, with metadata, 90% quality WebP image
|
|
||||||
// data
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
```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(input)
|
|
||||||
.extract(top, left, width, height)
|
|
||||||
.toFile(output);
|
|
||||||
// Extract a region of the input image, saving in the same format.
|
|
||||||
```
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
sharp(input)
|
|
||||||
.extract(topOffsetPre, leftOffsetPre, widthPre, heightPre)
|
|
||||||
.resize(width, height)
|
|
||||||
.extract(topOffsetPost, leftOffsetPost, widthPost, heightPost)
|
|
||||||
.toFile(output);
|
|
||||||
// Extract a region, resize, then extract from the resized image
|
|
||||||
```
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
sharp(inputBuffer)
|
|
||||||
.resize(200, 300)
|
|
||||||
.interpolateWith(sharp.interpolator.nohalo)
|
|
||||||
.background('white')
|
|
||||||
.embed()
|
|
||||||
.toFile('output.tiff')
|
|
||||||
.then(function() {
|
|
||||||
// output.tiff is a 200 pixels wide and 300 pixels high image
|
|
||||||
// containing a bicubic scaled version, embedded on a white canvas,
|
|
||||||
// of the image data in inputBuffer
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
sharp('input.gif')
|
|
||||||
.resize(200, 300)
|
|
||||||
.background({r: 0, g: 0, b: 0, a: 0})
|
|
||||||
.embed()
|
|
||||||
.webp()
|
|
||||||
.toBuffer(function(err, outputBuffer) {
|
|
||||||
if (err) {
|
|
||||||
throw err;
|
|
||||||
}
|
|
||||||
// outputBuffer contains WebP image data of a 200 pixels wide and 300 pixels high
|
|
||||||
// containing a scaled version, embedded on a transparent canvas, of input.gif
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
sharp(inputBuffer)
|
|
||||||
.resize(200, 200)
|
|
||||||
.max()
|
|
||||||
.jpeg()
|
|
||||||
.toBuffer().then(function(outputBuffer) {
|
|
||||||
// outputBuffer contains JPEG image data no wider than 200 pixels and no higher
|
|
||||||
// than 200 pixels regardless of the inputBuffer image dimensions
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
## API
|
|
||||||
|
|
||||||
### Input methods
|
|
||||||
|
|
||||||
#### sharp([input])
|
|
||||||
|
|
||||||
Constructor to which further methods are chained. `input`, if present, can be one of:
|
|
||||||
|
|
||||||
* Buffer containing JPEG, PNG, WebP or TIFF image data, or
|
|
||||||
* String containing the filename of an image, with most major formats supported.
|
|
||||||
|
|
||||||
The object returned implements the [stream.Duplex](http://nodejs.org/api/stream.html#stream_class_stream_duplex) class.
|
|
||||||
|
|
||||||
JPEG, PNG, WebP or TIFF 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.
|
|
||||||
|
|
||||||
#### metadata([callback])
|
|
||||||
|
|
||||||
Fast access to image metadata without decoding any compressed image data.
|
|
||||||
|
|
||||||
`callback`, if present, gets the arguments `(err, metadata)` where `metadata` has the attributes:
|
|
||||||
|
|
||||||
* `format`: Name of decoder to be used to decompress image data e.g. `jpeg`, `png`, `webp` (for file-based input additionally `tiff` and `magick`)
|
|
||||||
* `width`: Number of pixels wide
|
|
||||||
* `height`: Number of pixels high
|
|
||||||
* `space`: Name of colour space interpretation e.g. `srgb`, `rgb`, `scrgb`, `cmyk`, `lab`, `xyz`, `b-w` [...](https://github.com/jcupitt/libvips/blob/master/libvips/iofuncs/enumtypes.c#L522)
|
|
||||||
* `channels`: Number of bands e.g. `3` for sRGB, `4` for CMYK
|
|
||||||
* `hasProfile`: Boolean indicating the presence of an embedded ICC profile
|
|
||||||
* `hasAlpha`: Boolean indicating the presence of an alpha transparency channel
|
|
||||||
* `orientation`: Number value of the EXIF Orientation header, if present
|
|
||||||
|
|
||||||
A Promises/A+ promise is returned when `callback` is not provided.
|
|
||||||
|
|
||||||
#### 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.
|
|
||||||
|
|
||||||
`width` is the Number of pixels wide the resultant image should be. Use `null` or `undefined` to auto-scale the width to match the height.
|
|
||||||
|
|
||||||
`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.
|
|
||||||
|
|
||||||
#### extract(top, left, width, height)
|
|
||||||
|
|
||||||
Extract a region of the image. Can be used with or without a `resize` operation.
|
|
||||||
|
|
||||||
`top` and `left` are the offset, in pixels, from the top-left corner.
|
|
||||||
|
|
||||||
`width` and `height` are the dimensions of the extracted image.
|
|
||||||
|
|
||||||
Use `extract` before `resize` for pre-resize extraction. Use `extract` after `resize` for post-resize extraction. Use `extract` before and after for both.
|
|
||||||
|
|
||||||
#### crop([gravity])
|
|
||||||
|
|
||||||
Crop the resized image to the exact size specified, the default behaviour.
|
|
||||||
|
|
||||||
`gravity`, if present, is an attribute of the `sharp.gravity` Object e.g. `sharp.gravity.north`.
|
|
||||||
|
|
||||||
Possible values are `north`, `east`, `south`, `west`, `center` and `centre`. The default gravity is `center`/`centre`.
|
|
||||||
|
|
||||||
#### 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`.
|
|
||||||
|
|
||||||
#### background(rgba)
|
|
||||||
|
|
||||||
Set the background for the `embed` and `flatten` operations.
|
|
||||||
|
|
||||||
`rgba` is parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha.
|
|
||||||
|
|
||||||
The alpha value is a float between `0` (transparent) and `1` (opaque).
|
|
||||||
|
|
||||||
The default background is `{r: 0, g: 0, b: 0, a: 1}`, black without transparency.
|
|
||||||
|
|
||||||
#### embed()
|
|
||||||
|
|
||||||
Preserving aspect ratio, resize the image to the maximum `width` or `height` specified then embed on a background of the exact `width` and `height` specified.
|
|
||||||
|
|
||||||
If the background contains an alpha value then WebP and PNG format output images will contain an alpha channel, even when the input image does not.
|
|
||||||
|
|
||||||
#### flatten()
|
|
||||||
|
|
||||||
Merge alpha transparency channel, if any, with `background`.
|
|
||||||
|
|
||||||
#### rotate([angle])
|
|
||||||
|
|
||||||
Rotate the output image by either an explicit angle or auto-orient based on the EXIF `Orientation` tag.
|
|
||||||
|
|
||||||
`angle`, if present, is a Number with a value of `0`, `90`, `180` or `270`.
|
|
||||||
|
|
||||||
Use this method without `angle` to determine the angle from EXIF data. Mirroring is supported and may infer the use of a `flip` operation.
|
|
||||||
|
|
||||||
#### flip()
|
|
||||||
|
|
||||||
Flip the image about the vertical Y axis. This always occurs after rotation, if any.
|
|
||||||
|
|
||||||
#### flop()
|
|
||||||
|
|
||||||
Flop the image about the horizontal X axis. This always occurs after rotation, if any.
|
|
||||||
|
|
||||||
#### 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".
|
|
||||||
|
|
||||||
#### blur([sigma])
|
|
||||||
|
|
||||||
When used without parameters, performs a fast, mild blur of the output image. This typically reduces performance by 10%.
|
|
||||||
|
|
||||||
When a `sigma` is provided, performs a slower, more accurate Gaussian blur. This typically reduces performance by 25%.
|
|
||||||
|
|
||||||
* `sigma`, if present, is a Number between 0.3 and 1000 representing the approximate blur radius in pixels.
|
|
||||||
|
|
||||||
#### sharpen([radius], [flat], [jagged])
|
|
||||||
|
|
||||||
When used without parameters, performs a fast, mild sharpen of the output image. This typically reduces performance by 10%.
|
|
||||||
|
|
||||||
When a `radius` is provided, performs a slower, more accurate sharpen of the L channel in the LAB colour space. Separate control over the level of sharpening in "flat" and "jagged" areas is available. This typically reduces performance by 50%.
|
|
||||||
|
|
||||||
* `radius`, if present, is an integral Number representing the sharpen mask radius in pixels.
|
|
||||||
* `flat`, if present, is a Number representing the level of sharpening to apply to "flat" areas, defaulting to a value of 1.0.
|
|
||||||
* `jagged`, if present, is a Number representing the level of sharpening to apply to "jagged" areas, defaulting to a value of 2.0.
|
|
||||||
|
|
||||||
#### interpolateWith(interpolator)
|
|
||||||
|
|
||||||
Use the given interpolator for image resizing, where `interpolator` is an attribute of the `sharp.interpolator` Object e.g. `sharp.interpolator.bicubic`.
|
|
||||||
|
|
||||||
Possible interpolators, in order of performance, are:
|
|
||||||
|
|
||||||
* `nearest`: Use [nearest neighbour interpolation](http://en.wikipedia.org/wiki/Nearest-neighbor_interpolation), suitable for image enlargement only.
|
|
||||||
* `bilinear`: Use [bilinear interpolation](http://en.wikipedia.org/wiki/Bilinear_interpolation), the default and fastest image reduction interpolation.
|
|
||||||
* `bicubic`: Use [bicubic interpolation](http://en.wikipedia.org/wiki/Bicubic_interpolation), which typically reduces performance by 5%.
|
|
||||||
* `vertexSplitQuadraticBasisSpline`: Use [VSQBS interpolation](https://github.com/jcupitt/libvips/blob/master/libvips/resample/vsqbs.cpp#L48), which prevents "staircasing" and typically reduces performance by 5%.
|
|
||||||
* `locallyBoundedBicubic`: Use [LBB interpolation](https://github.com/jcupitt/libvips/blob/master/libvips/resample/lbb.cpp#L100), which prevents some "[acutance](http://en.wikipedia.org/wiki/Acutance)" and typically reduces performance by a factor of 2.
|
|
||||||
* `nohalo`: Use [Nohalo interpolation](http://eprints.soton.ac.uk/268086/), which prevents acutance and typically reduces performance by a factor of 3.
|
|
||||||
|
|
||||||
#### gamma([gamma])
|
|
||||||
|
|
||||||
Apply a gamma correction by reducing the encoding (darken) pre-resize at a factor of `1/gamma` then increasing the encoding (brighten) post-resize at a factor of `gamma`.
|
|
||||||
|
|
||||||
`gamma`, if present, is a Number betweem 1 and 3. The default value is `2.2`, a suitable approximation for sRGB images.
|
|
||||||
|
|
||||||
This can improve the perceived brightness of a resized image in non-linear colour spaces.
|
|
||||||
|
|
||||||
JPEG input images will not take advantage of the shrink-on-load performance optimisation when applying a gamma correction.
|
|
||||||
|
|
||||||
#### grayscale() / greyscale()
|
|
||||||
|
|
||||||
Convert to 8-bit greyscale; 256 shades of grey.
|
|
||||||
|
|
||||||
This is a linear operation. If the input image is in a non-linear colour space such as sRGB, use `gamma()` with `greyscale()` for the best results.
|
|
||||||
|
|
||||||
The output image will still be web-friendly sRGB and contain three (identical) channels.
|
|
||||||
|
|
||||||
### Output options
|
|
||||||
|
|
||||||
#### jpeg()
|
|
||||||
|
|
||||||
Use JPEG format for the output image.
|
|
||||||
|
|
||||||
#### png()
|
|
||||||
|
|
||||||
Use PNG format for the output image.
|
|
||||||
|
|
||||||
#### webp()
|
|
||||||
|
|
||||||
Use WebP format for the output image.
|
|
||||||
|
|
||||||
#### 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.
|
|
||||||
|
|
||||||
#### 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.
|
|
||||||
|
|
||||||
#### withMetadata()
|
|
||||||
|
|
||||||
Include all metadata (EXIF, XMP, IPTC) from the input image in the output image. This will also convert to and add the latest web-friendly v2 sRGB ICC profile.
|
|
||||||
|
|
||||||
The default behaviour is to strip all metadata and convert to the device-independent sRGB colour space.
|
|
||||||
|
|
||||||
#### 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 0 and 9.
|
|
||||||
|
|
||||||
#### withoutAdaptiveFiltering()
|
|
||||||
|
|
||||||
_Requires libvips 7.42.0+_
|
|
||||||
|
|
||||||
An advanced setting to disable adaptive row filtering for the lossless PNG output format.
|
|
||||||
|
|
||||||
### 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.
|
|
||||||
|
|
||||||
`callback`, if present, is called with two arguments `(err, info)` where:
|
|
||||||
|
|
||||||
* `err` contains an error message, if any.
|
|
||||||
* `info` contains the output image `format`, `size` (bytes), `width` and `height`.
|
|
||||||
|
|
||||||
A Promises/A+ promise is returned when `callback` is not provided.
|
|
||||||
|
|
||||||
#### toBuffer([callback])
|
|
||||||
|
|
||||||
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:
|
|
||||||
|
|
||||||
* `err` is an error message, if any.
|
|
||||||
* `buffer` is the output image data.
|
|
||||||
* `info` contains the output image `format`, `size` (bytes), `width` and `height`.
|
|
||||||
|
|
||||||
A Promises/A+ promise is returned when `callback` is not provided.
|
|
||||||
|
|
||||||
### Utility methods
|
|
||||||
|
|
||||||
#### sharp.cache([memory], [items])
|
|
||||||
|
|
||||||
If `memory` or `items` are provided, set the limits of _libvips'_ operation cache.
|
|
||||||
|
|
||||||
* `memory` is the maximum memory in MB to use for this cache, with a default value of 100
|
|
||||||
* `items` is the maximum number of operations to cache, with a default value of 500
|
|
||||||
|
|
||||||
This method always returns cache statistics, useful for determining how much working memory is required for a particular task.
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
var stats = sharp.cache(); // { current: 75, high: 99, memory: 100, items: 500 }
|
|
||||||
sharp.cache(200); // { current: 75, high: 99, memory: 200, items: 500 }
|
|
||||||
sharp.cache(50, 200); // { current: 49, high: 99, memory: 50, items: 200}
|
|
||||||
```
|
|
||||||
|
|
||||||
#### sharp.concurrency([threads])
|
|
||||||
|
|
||||||
`threads`, if provided, is the Number of threads _libvips'_ should create for processing each image. The default value is the number of CPU cores. A value of `0` will reset to this default.
|
|
||||||
|
|
||||||
This method always returns the current concurrency.
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
var threads = sharp.concurrency(); // 4
|
|
||||||
sharp.concurrency(2); // 2
|
|
||||||
sharp.concurrency(0); // 4
|
|
||||||
```
|
|
||||||
|
|
||||||
The maximum number of images that can be processed in parallel is limited by libuv's `UV_THREADPOOL_SIZE` environment variable.
|
|
||||||
|
|
||||||
#### sharp.counters()
|
|
||||||
|
|
||||||
Provides access to internal task counters.
|
|
||||||
|
|
||||||
* `queue` is the number of tasks this module has queued waiting for _libuv_ to provide a worker thread from its pool.
|
|
||||||
* `process` is the number of resize tasks currently being processed.
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
var counters = sharp.counters(); // { queue: 2, process: 4 }
|
|
||||||
```
|
|
||||||
|
|
||||||
## Testing
|
|
||||||
|
|
||||||
### Functional tests
|
|
||||||
|
|
||||||
#### Coverage
|
|
||||||
|
|
||||||
[](https://coveralls.io/r/lovell/sharp?branch=master)
|
[](https://coveralls.io/r/lovell/sharp?branch=master)
|
||||||
|
|
||||||
#### Ubuntu 12.04
|
### Documentation
|
||||||
|
|
||||||
[](https://travis-ci.org/lovell/sharp)
|
Visit [sharp.dimens.io](http://sharp.dimens.io/) for
|
||||||
|
complete installation instructions, API documentation,
|
||||||
|
benchmark tests and a changelog.
|
||||||
|
|
||||||
#### Centos 6.5
|
### Contributing
|
||||||
|
|
||||||
[](https://snap-ci.com/lovell/sharp/branch/master)
|
A [guide for contributors](https://github.com/lovell/sharp/blob/master/CONTRIBUTING.md)
|
||||||
|
covers reporting bugs, requesting features and submitting code changes.
|
||||||
|
|
||||||
#### It worked on my machine
|
### Licence
|
||||||
|
|
||||||
```
|
Copyright 2013, 2014, 2015 Lovell Fuller and contributors.
|
||||||
npm test
|
|
||||||
```
|
|
||||||
|
|
||||||
### Memory leak tests
|
|
||||||
|
|
||||||
```
|
|
||||||
cd sharp/test/leak
|
|
||||||
./leak.sh
|
|
||||||
```
|
|
||||||
|
|
||||||
Requires _valgrind_:
|
|
||||||
|
|
||||||
```
|
|
||||||
brew install valgrind
|
|
||||||
```
|
|
||||||
|
|
||||||
```
|
|
||||||
sudo apt-get install -qq valgrind
|
|
||||||
```
|
|
||||||
|
|
||||||
### Benchmark tests
|
|
||||||
|
|
||||||
```
|
|
||||||
cd sharp/test/bench
|
|
||||||
npm install
|
|
||||||
npm test
|
|
||||||
```
|
|
||||||
|
|
||||||
Requires both _ImageMagick_ and _GraphicsMagick_:
|
|
||||||
|
|
||||||
```
|
|
||||||
brew install imagemagick
|
|
||||||
brew install graphicsmagick
|
|
||||||
```
|
|
||||||
|
|
||||||
```
|
|
||||||
sudo apt-get install -qq imagemagick graphicsmagick libmagick++-dev
|
|
||||||
```
|
|
||||||
|
|
||||||
```
|
|
||||||
sudo yum install ImageMagick
|
|
||||||
sudo yum install -y http://download.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm
|
|
||||||
sudo yum install -y --enablerepo=epel GraphicsMagick
|
|
||||||
```
|
|
||||||
|
|
||||||
## Performance
|
|
||||||
|
|
||||||
### Test environment
|
|
||||||
|
|
||||||
* AWS EC2 [c3.xlarge](http://aws.amazon.com/ec2/instance-types/#Compute_Optimized)
|
|
||||||
* Ubuntu 14.04
|
|
||||||
* libvips 7.40.8
|
|
||||||
* liborc 0.4.22
|
|
||||||
|
|
||||||
### The contenders
|
|
||||||
|
|
||||||
* [imagemagick-native](https://github.com/mash/node-imagemagick-native) v1.2.2 - Supports Buffers only
|
|
||||||
* [imagemagick](https://github.com/yourdeveloper/node-imagemagick) v0.1.3 - Supports filesystem only and "has been unmaintained for a long time".
|
|
||||||
* [gm](https://github.com/aheckmann/gm) v1.16.0 - Fully featured wrapper around GraphicsMagick.
|
|
||||||
* sharp v0.6.2 - Caching within libvips disabled to ensure a fair comparison.
|
|
||||||
|
|
||||||
### The task
|
|
||||||
|
|
||||||
Decompress a 2725x2225 JPEG image, resize and crop to 720x480, then compress to JPEG.
|
|
||||||
|
|
||||||
### Results
|
|
||||||
|
|
||||||
| Module | Input | Output | Ops/sec | Speed-up |
|
|
||||||
| :-------------------- | :----- | :----- | ------: | -------: |
|
|
||||||
| imagemagick-native | buffer | buffer | 1.58 | 1 |
|
|
||||||
| imagemagick | file | file | 6.23 | 3.9 |
|
|
||||||
| gm | buffer | file | 5.32 | 3.4 |
|
|
||||||
| gm | buffer | buffer | 5.32 | 3.4 |
|
|
||||||
| gm | file | file | 5.36 | 3.4 |
|
|
||||||
| gm | file | buffer | 5.36 | 3.4 |
|
|
||||||
| sharp | buffer | file | 22.05 | 14.0 |
|
|
||||||
| sharp | buffer | buffer | 22.14 | 14.0 |
|
|
||||||
| sharp | file | file | 21.79 | 13.8 |
|
|
||||||
| sharp | file | buffer | 21.90 | 13.9 |
|
|
||||||
| sharp | stream | stream | 20.87 | 13.2 |
|
|
||||||
| sharp +promise | file | buffer | 21.89 | 13.9 |
|
|
||||||
| sharp +sharpen | file | buffer | 19.69 | 12.5 |
|
|
||||||
| sharp +progressive | file | buffer | 16.93 | 10.7 |
|
|
||||||
| sharp +sequentialRead | file | buffer | 21.60 | 13.7 |
|
|
||||||
|
|
||||||
You can expect greater performance with caching enabled (default) and using 8+ core machines.
|
|
||||||
|
|
||||||
## Thanks
|
|
||||||
|
|
||||||
This module would never have been possible without the help and code contributions of the following people:
|
|
||||||
|
|
||||||
* [John Cupitt](https://github.com/jcupitt)
|
|
||||||
* [Pierre Inglebert](https://github.com/pierreinglebert)
|
|
||||||
* [Jonathan Ong](https://github.com/jonathanong)
|
|
||||||
* [Chanon Sajjamanochai](https://github.com/chanon)
|
|
||||||
* [Juliano Julio](https://github.com/julianojulio)
|
|
||||||
* [Daniel Gasienica](https://github.com/gasi)
|
|
||||||
* [Julian Walker](https://github.com/julianwa)
|
|
||||||
* [Amit Pitaru](https://github.com/apitaru)
|
|
||||||
* [Brandon Aaron](https://github.com/brandonaaron)
|
|
||||||
* [Andreas Lind](https://github.com/papandreou)
|
|
||||||
|
|
||||||
Thank you!
|
|
||||||
|
|
||||||
## Licence
|
|
||||||
|
|
||||||
Copyright 2013, 2014 Lovell Fuller and contributors.
|
|
||||||
|
|
||||||
Licensed under the Apache License, Version 2.0 (the "License");
|
Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
you may not use this file except in compliance with the License.
|
you may not use this file except in compliance with the License.
|
||||||
You may obtain a copy of the License at [http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0.html)
|
You may obtain a copy of the License at
|
||||||
|
[http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0.html)
|
||||||
|
|
||||||
Unless required by applicable law or agreed to in writing, software
|
Unless required by applicable law or agreed to in writing, software
|
||||||
distributed under the License is distributed on an "AS IS" BASIS,
|
distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
|||||||
26
appveyor.yml
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
os: Visual Studio 2015
|
||||||
|
version: "{build}"
|
||||||
|
build: off
|
||||||
|
platform: x64
|
||||||
|
environment:
|
||||||
|
VIPS_VERSION_MAJOR_MINOR: 8.0
|
||||||
|
VIPS_VERSION_PATCH: 2
|
||||||
|
VIPS_WARNING: 0
|
||||||
|
matrix:
|
||||||
|
- nodejs_version: "0.10"
|
||||||
|
nodejs_exec: "node"
|
||||||
|
- nodejs_version: "0.12"
|
||||||
|
nodejs_exec: "node"
|
||||||
|
- nodejs_version: "2"
|
||||||
|
nodejs_exec: "iojs"
|
||||||
|
install:
|
||||||
|
- ps: $env:VIPS_VERSION = "$env:VIPS_VERSION_MAJOR_MINOR.$env:VIPS_VERSION_PATCH"
|
||||||
|
- ps: Write-Output "Fetching http://www.vips.ecs.soton.ac.uk/supported/$env:VIPS_VERSION_MAJOR_MINOR/win32/vips-dev-$env:VIPS_VERSION.zip"
|
||||||
|
- ps: Start-FileDownload http://www.vips.ecs.soton.ac.uk/supported/$env:VIPS_VERSION_MAJOR_MINOR/win32/vips-dev-$env:VIPS_VERSION.zip -FileName c:\vips-dev-$env:VIPS_VERSION.zip
|
||||||
|
- ps: Invoke-Expression "& 7z -y x c:\vips-dev-$env:VIPS_VERSION.zip -oc:\ | FIND /V `"ing `""
|
||||||
|
- ps: $env:VIPS_HOME = "c:\vips-dev-$env:VIPS_VERSION"
|
||||||
|
- ps: $env:PATH = "$env:VIPS_HOME\bin;$env:PATH"
|
||||||
|
- ps: Install-Product node $env:nodejs_version x86
|
||||||
|
- npm install --arch=ia32 --msvs_version=2013
|
||||||
|
test_script:
|
||||||
|
- npm run-script test-win32-%nodejs_exec%
|
||||||
76
binding.gyp
@@ -3,20 +3,56 @@
|
|||||||
'target_name': 'sharp',
|
'target_name': 'sharp',
|
||||||
'sources': [
|
'sources': [
|
||||||
'src/common.cc',
|
'src/common.cc',
|
||||||
'src/utilities.cc',
|
|
||||||
'src/metadata.cc',
|
'src/metadata.cc',
|
||||||
'src/resize.cc',
|
'src/operations.cc',
|
||||||
'src/sharp.cc'
|
'src/pipeline.cc',
|
||||||
|
'src/sharp.cc',
|
||||||
|
'src/utilities.cc'
|
||||||
],
|
],
|
||||||
'variables': {
|
'conditions': [
|
||||||
'PKG_CONFIG_PATH': '<!(which brew >/dev/null 2>&1 && eval $(brew --env) && echo $PKG_CONFIG_LIBDIR || true):$PKG_CONFIG_PATH:/usr/local/lib/pkgconfig:/usr/lib/pkgconfig'
|
['OS=="win"', {
|
||||||
},
|
'library_dirs': [
|
||||||
'libraries': [
|
'$(VIPS_HOME)/lib'
|
||||||
'<!(PKG_CONFIG_PATH="<(PKG_CONFIG_PATH)" pkg-config --libs vips)'
|
],
|
||||||
],
|
'libraries': [
|
||||||
'include_dirs': [
|
'libvips.dll.a',
|
||||||
'<!(PKG_CONFIG_PATH="<(PKG_CONFIG_PATH)" pkg-config --cflags vips glib-2.0)',
|
'glib-2.0.lib',
|
||||||
'<!(node -e "require(\'nan\')")'
|
'gobject-2.0.lib',
|
||||||
|
'gthread-2.0.lib',
|
||||||
|
'gmodule-2.0.lib',
|
||||||
|
'liblcms2.dll.a',
|
||||||
|
'libxml2.lib',
|
||||||
|
'intl.lib',
|
||||||
|
'libjpeg.dll.a',
|
||||||
|
'libexif.dll.a',
|
||||||
|
'libpng.lib',
|
||||||
|
'libtiff.dll.a',
|
||||||
|
'libMagickWand-6.Q16.dll.a',
|
||||||
|
'libMagickCore-6.Q16.dll.a',
|
||||||
|
'pango-1.0.lib',
|
||||||
|
'pangoft2-1.0.lib',
|
||||||
|
'libgsf-1.dll.a',
|
||||||
|
'libopenslide.dll.a',
|
||||||
|
'libfftw3.dll.a'
|
||||||
|
],
|
||||||
|
'include_dirs': [
|
||||||
|
'$(VIPS_HOME)/include',
|
||||||
|
'$(VIPS_HOME)/include/glib-2.0',
|
||||||
|
'$(VIPS_HOME)/lib/glib-2.0/include',
|
||||||
|
'<!(node -e "require(\'nan\')")'
|
||||||
|
]
|
||||||
|
}, {
|
||||||
|
'variables': {
|
||||||
|
'PKG_CONFIG_PATH': '<!(which brew >/dev/null 2>&1 && eval $(brew --env) && echo $PKG_CONFIG_LIBDIR || true):$PKG_CONFIG_PATH:/usr/local/lib/pkgconfig:/usr/lib/pkgconfig'
|
||||||
|
},
|
||||||
|
'libraries': [
|
||||||
|
'<!(PKG_CONFIG_PATH="<(PKG_CONFIG_PATH)" pkg-config --libs vips)'
|
||||||
|
],
|
||||||
|
'include_dirs': [
|
||||||
|
'<!(PKG_CONFIG_PATH="<(PKG_CONFIG_PATH)" pkg-config --cflags vips glib-2.0)',
|
||||||
|
'<!(node -e "require(\'nan\')")'
|
||||||
|
]
|
||||||
|
}]
|
||||||
],
|
],
|
||||||
'cflags_cc': [
|
'cflags_cc': [
|
||||||
'-std=c++0x',
|
'-std=c++0x',
|
||||||
@@ -33,6 +69,20 @@
|
|||||||
'-O3'
|
'-O3'
|
||||||
],
|
],
|
||||||
'MACOSX_DEPLOYMENT_TARGET': '10.7'
|
'MACOSX_DEPLOYMENT_TARGET': '10.7'
|
||||||
}
|
},
|
||||||
|
'msvs_settings': {
|
||||||
|
'VCCLCompilerTool': {
|
||||||
|
'ExceptionHandling': 1 # /EHsc
|
||||||
|
}
|
||||||
|
},
|
||||||
|
'configurations': {
|
||||||
|
'Release': {
|
||||||
|
'msvs_settings': {
|
||||||
|
'VCCLCompilerTool': {
|
||||||
|
'ExceptionHandling': 1,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
}]
|
}]
|
||||||
}
|
}
|
||||||
|
|||||||
597
docs/api.md
Normal file
@@ -0,0 +1,597 @@
|
|||||||
|
# API
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
var sharp = require('sharp');
|
||||||
|
```
|
||||||
|
|
||||||
|
### Input
|
||||||
|
|
||||||
|
#### sharp([input])
|
||||||
|
|
||||||
|
Constructor to which further methods are chained. `input`, if present, can be one of:
|
||||||
|
|
||||||
|
* Buffer containing JPEG, PNG, WebP, GIF* or TIFF image data, or
|
||||||
|
* String containing the filename of an image, with most major formats supported.
|
||||||
|
|
||||||
|
The object returned implements the
|
||||||
|
[stream.Duplex](http://nodejs.org/api/stream.html#stream_class_stream_duplex) class.
|
||||||
|
|
||||||
|
JPEG, PNG, WebP, GIF* or TIFF 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.
|
||||||
|
|
||||||
|
\* libvips 8.0.0+ is required for Buffer/Stream input of GIF and other `magick` formats.
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
sharp('input.jpg')
|
||||||
|
.resize(300, 200)
|
||||||
|
.toFile('output.jpg', function(err) {
|
||||||
|
// output.jpg is a 300 pixels wide and 200 pixels high image
|
||||||
|
// containing a scaled and cropped version of input.jpg
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
#### metadata([callback])
|
||||||
|
|
||||||
|
Fast access to image metadata without decoding any compressed image data.
|
||||||
|
|
||||||
|
`callback`, if present, gets the arguments `(err, metadata)` where `metadata` has the attributes:
|
||||||
|
|
||||||
|
* `format`: Name of decoder to be used to decompress image data e.g. `jpeg`, `png`, `webp` (for file-based input additionally `tiff`, `magick` and `openslide`)
|
||||||
|
* `width`: Number of pixels wide
|
||||||
|
* `height`: Number of pixels high
|
||||||
|
* `space`: Name of colour space interpretation e.g. `srgb`, `rgb`, `scrgb`, `cmyk`, `lab`, `xyz`, `b-w` [...](https://github.com/jcupitt/libvips/blob/master/libvips/iofuncs/enumtypes.c#L522)
|
||||||
|
* `channels`: Number of bands e.g. `3` for sRGB, `4` for CMYK
|
||||||
|
* `hasProfile`: Boolean indicating the presence of an embedded ICC profile
|
||||||
|
* `hasAlpha`: Boolean indicating the presence of an alpha transparency channel
|
||||||
|
* `orientation`: Number value of the EXIF Orientation header, if present
|
||||||
|
* `exif`: Buffer containing raw EXIF data, if present
|
||||||
|
* `icc`: Buffer containing raw [ICC](https://www.npmjs.com/package/icc) profile data, if present
|
||||||
|
|
||||||
|
A Promises/A+ promise is returned when `callback` is not provided.
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
var image = sharp(inputJpg);
|
||||||
|
image
|
||||||
|
.metadata()
|
||||||
|
.then(function(metadata) {
|
||||||
|
return image
|
||||||
|
.resize(Math.round(metadata.width / 2))
|
||||||
|
.webp()
|
||||||
|
.toBuffer();
|
||||||
|
})
|
||||||
|
.then(function(data) {
|
||||||
|
// data contains a WebP image half the width and height of the original JPEG
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
#### clone()
|
||||||
|
|
||||||
|
Takes a "snapshot" of the instance, returning a new instance.
|
||||||
|
Cloned instances inherit the input of their parent instance.
|
||||||
|
|
||||||
|
This allows multiple output Streams
|
||||||
|
and therefore multiple processing pipelines
|
||||||
|
to share a single input Stream.
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
var pipeline = sharp().rotate();
|
||||||
|
pipeline.clone().resize(800, 600).pipe(firstWritableStream);
|
||||||
|
pipeline.clone().extract(20, 20, 100, 100).pipe(secondWritableStream);
|
||||||
|
readableStream.pipe(pipeline);
|
||||||
|
// firstWritableStream receives auto-rotated, resized readableStream
|
||||||
|
// secondWritableStream receives auto-rotated, extracted region of readableStream
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 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.
|
||||||
|
|
||||||
|
#### limitInputPixels(pixels)
|
||||||
|
|
||||||
|
Do not process input images where the number of pixels (width * height) exceeds this limit.
|
||||||
|
|
||||||
|
`pixels` is the integral Number of pixels, with a value between 1 and the default 268402689 (0x3FFF * 0x3FFF).
|
||||||
|
|
||||||
|
### Resizing
|
||||||
|
|
||||||
|
#### resize([width], [height])
|
||||||
|
|
||||||
|
Scale output to `width` x `height`. By default, the resized image is cropped to the exact size specified.
|
||||||
|
|
||||||
|
`width` is the integral Number of pixels wide the resultant image should be, between 1 and 16383 (0x3FFF). Use `null` or `undefined` to auto-scale the width to match the height.
|
||||||
|
|
||||||
|
`height` is the integral Number of pixels high the resultant image should be, between 1 and 16383. Use `null` or `undefined` to auto-scale the height to match the width.
|
||||||
|
|
||||||
|
#### crop([gravity])
|
||||||
|
|
||||||
|
Crop the resized image to the exact size specified, the default behaviour.
|
||||||
|
|
||||||
|
`gravity`, if present, is an attribute of the `sharp.gravity` Object e.g. `sharp.gravity.north`.
|
||||||
|
|
||||||
|
Possible values are `north`, `east`, `south`, `west`, `center` and `centre`. The default gravity is `center`/`centre`.
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
var transformer = sharp()
|
||||||
|
.resize(300, 200)
|
||||||
|
.crop(sharp.gravity.north)
|
||||||
|
.on('error', function(err) {
|
||||||
|
console.log(err);
|
||||||
|
});
|
||||||
|
// Read image data from readableStream, resize and write image data to writableStream
|
||||||
|
readableStream.pipe(transformer).pipe(writableStream);
|
||||||
|
```
|
||||||
|
|
||||||
|
#### embed()
|
||||||
|
|
||||||
|
Preserving aspect ratio, resize the image to the
|
||||||
|
maximum `width` or `height` specified
|
||||||
|
then embed on a background of the exact
|
||||||
|
`width` and `height` specified.
|
||||||
|
|
||||||
|
If the background contains an alpha value
|
||||||
|
then WebP and PNG format output images will
|
||||||
|
contain an alpha channel,
|
||||||
|
even when the input image does not.
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
sharp('input.gif')
|
||||||
|
.resize(200, 300)
|
||||||
|
.background({r: 0, g: 0, b: 0, a: 0})
|
||||||
|
.embed()
|
||||||
|
.toFormat(sharp.format.webp)
|
||||||
|
.toBuffer(function(err, outputBuffer) {
|
||||||
|
if (err) {
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
// outputBuffer contains WebP image data of a 200 pixels wide and 300 pixels high
|
||||||
|
// containing a scaled version, embedded on a transparent canvas, of input.gif
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
#### max()
|
||||||
|
|
||||||
|
Preserving aspect ratio,
|
||||||
|
resize the image to be as large as possible
|
||||||
|
while ensuring its dimensions are less than or equal to
|
||||||
|
the `width` and `height` specified.
|
||||||
|
|
||||||
|
Both `width` and `height` must be provided via
|
||||||
|
`resize` otherwise the behaviour will default to `crop`.
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
sharp(inputBuffer)
|
||||||
|
.resize(200, 200)
|
||||||
|
.max()
|
||||||
|
.toFormat('jpeg')
|
||||||
|
.toBuffer()
|
||||||
|
.then(function(outputBuffer) {
|
||||||
|
// outputBuffer contains JPEG image data no wider than 200 pixels and no higher
|
||||||
|
// than 200 pixels regardless of the inputBuffer image dimensions
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
#### min()
|
||||||
|
|
||||||
|
Preserving aspect ratio,
|
||||||
|
resize the image to be as small as possible
|
||||||
|
while ensuring its dimensions are greater than or equal to
|
||||||
|
the `width` and `height` specified.
|
||||||
|
|
||||||
|
Both `width` and `height` must be provided via `resize` otherwise the behaviour will default to `crop`.
|
||||||
|
|
||||||
|
#### 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*".
|
||||||
|
|
||||||
|
#### ignoreAspectRatio()
|
||||||
|
|
||||||
|
Ignoring the aspect ratio of the input, stretch the image to the exact `width` and/or `height` provided via `resize`.
|
||||||
|
|
||||||
|
#### interpolateWith(interpolator)
|
||||||
|
|
||||||
|
Use the given interpolator for image resizing, where `interpolator` is an attribute of the `sharp.interpolator` Object e.g. `sharp.interpolator.bicubic`.
|
||||||
|
|
||||||
|
Possible interpolators, in order of performance, are:
|
||||||
|
|
||||||
|
* `nearest`: Use [nearest neighbour interpolation](http://en.wikipedia.org/wiki/Nearest-neighbor_interpolation), suitable for image enlargement only.
|
||||||
|
* `bilinear`: Use [bilinear interpolation](http://en.wikipedia.org/wiki/Bilinear_interpolation), the default and fastest image reduction interpolation.
|
||||||
|
* `bicubic`: Use [bicubic interpolation](http://en.wikipedia.org/wiki/Bicubic_interpolation), which typically reduces performance by 5%.
|
||||||
|
* `vertexSplitQuadraticBasisSpline`: Use [VSQBS interpolation](https://github.com/jcupitt/libvips/blob/master/libvips/resample/vsqbs.cpp#L48), which prevents "staircasing" and typically reduces performance by 5%.
|
||||||
|
* `locallyBoundedBicubic`: Use [LBB interpolation](https://github.com/jcupitt/libvips/blob/master/libvips/resample/lbb.cpp#L100), which prevents some "[acutance](http://en.wikipedia.org/wiki/Acutance)" and typically reduces performance by a factor of 2.
|
||||||
|
* `nohalo`: Use [Nohalo interpolation](http://eprints.soton.ac.uk/268086/), which prevents acutance and typically reduces performance by a factor of 3.
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
sharp(inputBuffer)
|
||||||
|
.resize(200, 300)
|
||||||
|
.interpolateWith(sharp.interpolator.nohalo)
|
||||||
|
.background('white')
|
||||||
|
.embed()
|
||||||
|
.toFile('output.tiff')
|
||||||
|
.then(function() {
|
||||||
|
// output.tiff is a 200 pixels wide and 300 pixels high image
|
||||||
|
// containing a nohalo scaled version, embedded on a white canvas,
|
||||||
|
// of the image data in inputBuffer
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
### Operations
|
||||||
|
|
||||||
|
#### extract(top, left, width, height)
|
||||||
|
|
||||||
|
Extract a region of the image. Can be used with or without a `resize` operation.
|
||||||
|
|
||||||
|
`top` and `left` are the offset, in pixels, from the top-left corner.
|
||||||
|
|
||||||
|
`width` and `height` are the dimensions of the extracted image.
|
||||||
|
|
||||||
|
Use `extract` before `resize` for pre-resize extraction. Use `extract` after `resize` for post-resize extraction. Use `extract` before and after for both.
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
sharp(input)
|
||||||
|
.extract(top, left, width, height)
|
||||||
|
.toFile(output, function(err) {
|
||||||
|
// Extract a region of the input image, saving in the same format.
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
sharp(input)
|
||||||
|
.extract(topOffsetPre, leftOffsetPre, widthPre, heightPre)
|
||||||
|
.resize(width, height)
|
||||||
|
.extract(topOffsetPost, leftOffsetPost, widthPost, heightPost)
|
||||||
|
.toFile(output, function(err) {
|
||||||
|
// Extract a region, resize, then extract from the resized image
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
#### background(rgba)
|
||||||
|
|
||||||
|
Set the background for the `embed` and `flatten` operations.
|
||||||
|
|
||||||
|
`rgba` is parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha.
|
||||||
|
|
||||||
|
The alpha value is a float between `0` (transparent) and `1` (opaque).
|
||||||
|
|
||||||
|
The default background is `{r: 0, g: 0, b: 0, a: 1}`, black without transparency.
|
||||||
|
|
||||||
|
#### flatten()
|
||||||
|
|
||||||
|
Merge alpha transparency channel, if any, with `background`.
|
||||||
|
|
||||||
|
#### rotate([angle])
|
||||||
|
|
||||||
|
Rotate the output image by either an explicit angle or auto-orient based on the EXIF `Orientation` tag.
|
||||||
|
|
||||||
|
`angle`, if present, is a Number with a value of `0`, `90`, `180` or `270`.
|
||||||
|
|
||||||
|
Use this method without `angle` to determine the angle from EXIF data. Mirroring is supported and may infer the use of a `flip` operation.
|
||||||
|
|
||||||
|
Method order is important when both rotating and extracting regions, for example `rotate(x).extract(y)` will produce a different result to `extract(y).rotate(x)`.
|
||||||
|
|
||||||
|
The use of `rotate` implies the removal of the EXIF `Orientation` tag, if any.
|
||||||
|
|
||||||
|
```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 dimensions of the resized image
|
||||||
|
});
|
||||||
|
readableStream.pipe(pipeline);
|
||||||
|
```
|
||||||
|
|
||||||
|
#### flip()
|
||||||
|
|
||||||
|
Flip the image about the vertical Y axis. This always occurs after rotation, if any.
|
||||||
|
The use of `flip` implies the removal of the EXIF `Orientation` tag, if any.
|
||||||
|
|
||||||
|
#### flop()
|
||||||
|
|
||||||
|
Flop the image about the horizontal X axis. This always occurs after rotation, if any.
|
||||||
|
The use of `flop` implies the removal of the EXIF `Orientation` tag, if any.
|
||||||
|
|
||||||
|
#### blur([sigma])
|
||||||
|
|
||||||
|
When used without parameters, performs a fast, mild blur of the output image. This typically reduces performance by 10%.
|
||||||
|
|
||||||
|
When a `sigma` is provided, performs a slower, more accurate Gaussian blur. This typically reduces performance by 25%.
|
||||||
|
|
||||||
|
* `sigma`, if present, is a Number between 0.3 and 1000 representing the approximate blur radius in pixels.
|
||||||
|
|
||||||
|
#### sharpen([radius], [flat], [jagged])
|
||||||
|
|
||||||
|
When used without parameters, performs a fast, mild sharpen of the output image. This typically reduces performance by 10%.
|
||||||
|
|
||||||
|
When a `radius` is provided, performs a slower, more accurate sharpen of the L channel in the LAB colour space. Separate control over the level of sharpening in "flat" and "jagged" areas is available. This typically reduces performance by 50%.
|
||||||
|
|
||||||
|
* `radius`, if present, is an integral Number representing the sharpen mask radius in pixels.
|
||||||
|
* `flat`, if present, is a Number representing the level of sharpening to apply to "flat" areas, defaulting to a value of 1.0.
|
||||||
|
* `jagged`, if present, is a Number representing the level of sharpening to apply to "jagged" areas, defaulting to a value of 2.0.
|
||||||
|
|
||||||
|
#### gamma([gamma])
|
||||||
|
|
||||||
|
Apply a gamma correction by reducing the encoding (darken) pre-resize at a factor of `1/gamma` then increasing the encoding (brighten) post-resize at a factor of `gamma`.
|
||||||
|
|
||||||
|
`gamma`, if present, is a Number betweem 1 and 3. The default value is `2.2`, a suitable approximation for sRGB images.
|
||||||
|
|
||||||
|
This can improve the perceived brightness of a resized image in non-linear colour spaces.
|
||||||
|
|
||||||
|
JPEG input images will not take advantage of the shrink-on-load performance optimisation when applying a gamma correction.
|
||||||
|
|
||||||
|
#### grayscale() / greyscale()
|
||||||
|
|
||||||
|
Convert to 8-bit greyscale; 256 shades of grey.
|
||||||
|
|
||||||
|
This is a linear operation. If the input image is in a non-linear colour space such as sRGB, use `gamma()` with `greyscale()` for the best results.
|
||||||
|
|
||||||
|
The output image will still be web-friendly sRGB and contain three (identical) channels.
|
||||||
|
|
||||||
|
#### normalize() / normalise()
|
||||||
|
|
||||||
|
Enhance output image contrast by stretching its luminance to cover the full dynamic range. This typically reduces performance by 30%.
|
||||||
|
|
||||||
|
#### overlayWith(filename)
|
||||||
|
|
||||||
|
_Experimental_
|
||||||
|
|
||||||
|
Alpha composite `filename` over the processed (resized, extracted) image. The dimensions of the two images must match.
|
||||||
|
|
||||||
|
* `filename` is a String containing the filename of an image with an alpha channel.
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
sharp('input.png')
|
||||||
|
.rotate(180)
|
||||||
|
.resize(300)
|
||||||
|
.flatten()
|
||||||
|
.background('#ff6600')
|
||||||
|
.overlayWith('overlay.png')
|
||||||
|
.sharpen()
|
||||||
|
.withMetadata()
|
||||||
|
.quality(90)
|
||||||
|
.webp()
|
||||||
|
.toBuffer()
|
||||||
|
.then(function(outputBuffer) {
|
||||||
|
// outputBuffer contains upside down, 300px wide, alpha channel flattened
|
||||||
|
// onto orange background, composited with overlay.png, sharpened,
|
||||||
|
// with metadata, 90% quality WebP image data. Phew!
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
### Output
|
||||||
|
|
||||||
|
#### 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, TIFF and DZI supported.
|
||||||
|
|
||||||
|
`callback`, if present, is called with two arguments `(err, info)` where:
|
||||||
|
|
||||||
|
* `err` contains an error message, if any.
|
||||||
|
* `info` contains the output image `format`, `size` (bytes), `width` and `height`.
|
||||||
|
|
||||||
|
A Promises/A+ promise is returned when `callback` is not provided.
|
||||||
|
|
||||||
|
#### toBuffer([callback])
|
||||||
|
|
||||||
|
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:
|
||||||
|
|
||||||
|
* `err` is an error message, if any.
|
||||||
|
* `buffer` is the output image data.
|
||||||
|
* `info` contains the output image `format`, `size` (bytes), `width` and `height`.
|
||||||
|
|
||||||
|
A Promises/A+ promise is returned when `callback` is not provided.
|
||||||
|
|
||||||
|
#### jpeg()
|
||||||
|
|
||||||
|
Use JPEG format for the output image.
|
||||||
|
|
||||||
|
#### png()
|
||||||
|
|
||||||
|
Use PNG format for the output image.
|
||||||
|
|
||||||
|
#### webp()
|
||||||
|
|
||||||
|
Use WebP format for the output image.
|
||||||
|
|
||||||
|
#### raw()
|
||||||
|
|
||||||
|
_Requires libvips 7.42.0+_
|
||||||
|
|
||||||
|
Provide raw, uncompressed uint8 (unsigned char) image data for Buffer and Stream based output.
|
||||||
|
|
||||||
|
The number of channels depends on the input image and selected options.
|
||||||
|
|
||||||
|
* 1 channel for images converted to `greyscale()`, with each byte representing one pixel.
|
||||||
|
* 3 channels for colour images without alpha transparency, with bytes ordered \[red, green, blue, red, green, blue, etc.\]).
|
||||||
|
* 4 channels for colour images with alpha transparency, with bytes ordered \[red, green, blue, alpha, red, green, blue, alpha, etc.\].
|
||||||
|
|
||||||
|
#### toFormat(format)
|
||||||
|
|
||||||
|
Convenience method for the above output format methods, where `format` is either:
|
||||||
|
|
||||||
|
* an attribute of the `sharp.format` Object e.g. `sharp.format.jpeg`, or
|
||||||
|
* a String containing `jpeg`, `png`, `webp` or `raw`.
|
||||||
|
|
||||||
|
#### 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.
|
||||||
|
|
||||||
|
#### 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.
|
||||||
|
|
||||||
|
#### withMetadata([metadata])
|
||||||
|
|
||||||
|
Include all metadata (EXIF, XMP, IPTC) from the input image in the output image.
|
||||||
|
This will also convert to and add the latest web-friendly v2 sRGB ICC profile.
|
||||||
|
|
||||||
|
The optional `metadata` parameter, if present, is an Object with the attributes to update.
|
||||||
|
New attributes cannot be inserted, only existing attributes updated.
|
||||||
|
|
||||||
|
* `orientation` is an integral Number between 0 and 7, used to update the value of the EXIF `Orientation` tag.
|
||||||
|
This has no effect if the input image does not have an EXIF `Orientation` tag.
|
||||||
|
|
||||||
|
The default behaviour, when `withMetadata` is not used, is to strip all metadata and convert to the device-independent sRGB colour space.
|
||||||
|
|
||||||
|
#### tile([size], [overlap])
|
||||||
|
|
||||||
|
The size and overlap, in pixels, of square Deep Zoom image pyramid tiles.
|
||||||
|
|
||||||
|
* `size` is an integral Number between 1 and 8192. The default value is 256 pixels.
|
||||||
|
* `overlap` is an integral Number between 0 and 8192. The default value is 0 pixels.
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
sharp('input.tiff').tile(256).toFile('output.dzi', function(err, info) {
|
||||||
|
// The output.dzi file is the XML format Deep Zoom definition
|
||||||
|
// The output_files directory contains 256x256 pixel tiles grouped by zoom level
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
#### withoutChromaSubsampling()
|
||||||
|
|
||||||
|
Disable the use of [chroma subsampling](http://en.wikipedia.org/wiki/Chroma_subsampling) with JPEG output (4:4:4).
|
||||||
|
|
||||||
|
This can improve colour representation at higher quality settings (90+),
|
||||||
|
but usually increases output file size and typically reduces performance by 25%.
|
||||||
|
|
||||||
|
The default behaviour is to use chroma subsampling (4:2:0).
|
||||||
|
|
||||||
|
#### 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 0 and 9.
|
||||||
|
|
||||||
|
#### withoutAdaptiveFiltering()
|
||||||
|
|
||||||
|
_Requires libvips 7.42.0+_
|
||||||
|
|
||||||
|
An advanced setting to disable adaptive row filtering for the lossless PNG output format.
|
||||||
|
|
||||||
|
#### trellisQuantisation() / trellisQuantization()
|
||||||
|
|
||||||
|
_Requires libvips 8.0.0+ compiled against mozjpeg 3.0+_
|
||||||
|
|
||||||
|
An advanced setting to apply the use of
|
||||||
|
[trellis quantisation](http://en.wikipedia.org/wiki/Trellis_quantization) with JPEG output.
|
||||||
|
Reduces file size and slightly increases relative quality at the cost of increased compression time.
|
||||||
|
|
||||||
|
#### overshootDeringing()
|
||||||
|
|
||||||
|
_Requires libvips 8.0.0+ compiled against mozjpeg 3.0+_
|
||||||
|
|
||||||
|
An advanced setting to reduce the effects of
|
||||||
|
[ringing](http://en.wikipedia.org/wiki/Ringing_%28signal%29) in JPEG output,
|
||||||
|
in particular where black text appears on a white background (or vice versa).
|
||||||
|
|
||||||
|
#### optimiseScans() / optimizeScans()
|
||||||
|
|
||||||
|
_Requires libvips 8.0.0+ compiled against mozjpeg 3.0+_
|
||||||
|
|
||||||
|
An advanced setting for progressive (interlace) JPEG output.
|
||||||
|
Calculates which spectrum of DCT coefficients uses the fewest bits.
|
||||||
|
Usually reduces file size at the cost of increased compression time.
|
||||||
|
|
||||||
|
### Attributes
|
||||||
|
|
||||||
|
#### format
|
||||||
|
|
||||||
|
An Object containing nested boolean values
|
||||||
|
representing the available input and output formats/methods,
|
||||||
|
for example:
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
> console.dir(sharp.format);
|
||||||
|
|
||||||
|
{ jpeg: { id: 'jpeg',
|
||||||
|
input: { file: true, buffer: true, stream: true },
|
||||||
|
output: { file: true, buffer: true, stream: true } },
|
||||||
|
png: { id: 'png',
|
||||||
|
input: { file: true, buffer: true, stream: true },
|
||||||
|
output: { file: true, buffer: true, stream: true } },
|
||||||
|
webp: { id: 'webp',
|
||||||
|
input: { file: true, buffer: true, stream: true },
|
||||||
|
output: { file: true, buffer: true, stream: true } },
|
||||||
|
tiff: { id: 'tiff',
|
||||||
|
input: { file: true, buffer: true, stream: true },
|
||||||
|
output: { file: true, buffer: false, stream: false } },
|
||||||
|
magick: { id: 'magick',
|
||||||
|
input: { file: true, buffer: true, stream: true },
|
||||||
|
output: { file: false, buffer: false, stream: false } },
|
||||||
|
raw: { id: 'raw',
|
||||||
|
input: { file: false, buffer: false, stream: false },
|
||||||
|
output: { file: false, buffer: true, stream: true } } }
|
||||||
|
```
|
||||||
|
|
||||||
|
#### queue
|
||||||
|
|
||||||
|
An EventEmitter that emits a `change` event when a task is either:
|
||||||
|
|
||||||
|
* queued, waiting for _libuv_ to provide a worker thread
|
||||||
|
* complete
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
sharp.queue.on('change', function(queueLength) {
|
||||||
|
console.log('Queue contains ' + queueLength + ' task(s)');
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
### Utilities
|
||||||
|
|
||||||
|
#### sharp.cache([memory], [items])
|
||||||
|
|
||||||
|
If `memory` or `items` are provided, set the limits of _libvips'_ operation cache.
|
||||||
|
|
||||||
|
* `memory` is the maximum memory in MB to use for this cache, with a default value of 100
|
||||||
|
* `items` is the maximum number of operations to cache, with a default value of 500
|
||||||
|
|
||||||
|
This method always returns cache statistics, useful for determining how much working memory is required for a particular task.
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
var stats = sharp.cache(); // { current: 75, high: 99, memory: 100, items: 500 }
|
||||||
|
sharp.cache(200); // { current: 75, high: 99, memory: 200, items: 500 }
|
||||||
|
sharp.cache(50, 200); // { current: 49, high: 99, memory: 50, items: 200}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### sharp.concurrency([threads])
|
||||||
|
|
||||||
|
`threads`, if provided, is the Number of threads _libvips'_ should create for processing each image. The default value is the number of CPU cores. A value of `0` will reset to this default.
|
||||||
|
|
||||||
|
This method always returns the current concurrency.
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
var threads = sharp.concurrency(); // 4
|
||||||
|
sharp.concurrency(2); // 2
|
||||||
|
sharp.concurrency(0); // 4
|
||||||
|
```
|
||||||
|
|
||||||
|
The maximum number of images that can be processed in parallel is limited by libuv's `UV_THREADPOOL_SIZE` environment variable.
|
||||||
|
|
||||||
|
#### sharp.counters()
|
||||||
|
|
||||||
|
Provides access to internal task counters.
|
||||||
|
|
||||||
|
* `queue` is the number of tasks this module has queued waiting for _libuv_ to provide a worker thread from its pool.
|
||||||
|
* `process` is the number of resize tasks currently being processed.
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
var counters = sharp.counters(); // { queue: 2, process: 4 }
|
||||||
|
```
|
||||||
73
docs/changelog.md
Normal file
@@ -0,0 +1,73 @@
|
|||||||
|
# Changelog
|
||||||
|
|
||||||
|
### v0.11 - "*knife*"
|
||||||
|
|
||||||
|
#### v0.11.1 - 12<sup>th</sup> August 2015
|
||||||
|
|
||||||
|
* Silence MSVC warning: "C4530: C++ exception handler used, but unwind semantics are not enabled".
|
||||||
|
[#244](https://github.com/lovell/sharp/pull/244)
|
||||||
|
[@TheThing](https://github.com/TheThing)
|
||||||
|
|
||||||
|
* Suppress gamma correction for input image with alpha transparency.
|
||||||
|
[#249](https://github.com/lovell/sharp/issues/249)
|
||||||
|
[@compeak](https://github.com/compeak)
|
||||||
|
|
||||||
|
#### v0.11.0 - 15<sup>th</sup> July 2015
|
||||||
|
|
||||||
|
* Allow alpha transparency compositing via new `overlayWith` method.
|
||||||
|
[#97](https://github.com/lovell/sharp/issues/97)
|
||||||
|
[@gasi](https://github.com/gasi)
|
||||||
|
|
||||||
|
* Expose raw ICC profile data as a Buffer when using `metadata`.
|
||||||
|
[#129](https://github.com/lovell/sharp/issues/129)
|
||||||
|
[@homerjam](https://github.com/homerjam)
|
||||||
|
|
||||||
|
* Allow image header updates via a parameter passed to existing `withMetadata` method.
|
||||||
|
Provide initial support for EXIF `Orientation` tag,
|
||||||
|
which if present is now removed when using `rotate`, `flip` or `flop`.
|
||||||
|
[#189](https://github.com/lovell/sharp/issues/189)
|
||||||
|
[@h2non](https://github.com/h2non)
|
||||||
|
|
||||||
|
* Tighten constructor parameter checks.
|
||||||
|
[#221](https://github.com/lovell/sharp/issues/221)
|
||||||
|
[@mikemorris](https://github.com/mikemorris)
|
||||||
|
|
||||||
|
* Allow one input Stream to be shared with two or more output Streams via new `clone` method.
|
||||||
|
[#235](https://github.com/lovell/sharp/issues/235)
|
||||||
|
[@jaubourg](https://github.com/jaubourg)
|
||||||
|
|
||||||
|
* Use `round` instead of `floor` when auto-scaling dimensions to avoid floating-point rounding errors.
|
||||||
|
[#238](https://github.com/lovell/sharp/issues/238)
|
||||||
|
[@richardadjogah](https://github.com/richardadjogah)
|
||||||
|
|
||||||
|
### v0.10 - "*judgment*"
|
||||||
|
|
||||||
|
#### v0.10.1 - 1<sup>st</sup> June 2015
|
||||||
|
|
||||||
|
* Allow embed of image with alpha transparency onto non-transparent background.
|
||||||
|
[#204](https://github.com/lovell/sharp/issues/204)
|
||||||
|
[@mikemliu](https://github.com/mikemliu)
|
||||||
|
|
||||||
|
* Include C standard library for `atoi` as Xcode 6.3 appears to no longer do this.
|
||||||
|
[#228](https://github.com/lovell/sharp/issues/228)
|
||||||
|
[@doggan](https://github.com/doggan)
|
||||||
|
|
||||||
|
#### v0.10.0 - 23<sup>rd</sup> April 2015
|
||||||
|
|
||||||
|
* Add support for Windows (x86).
|
||||||
|
[#19](https://github.com/lovell/sharp/issues/19)
|
||||||
|
[@DullReferenceException](https://github.com/DullReferenceException)
|
||||||
|
[@itsananderson](https://github.com/itsananderson)
|
||||||
|
|
||||||
|
* Add support for Openslide input and DeepZoom output.
|
||||||
|
[#146](https://github.com/lovell/sharp/issues/146)
|
||||||
|
[@mvictoras](https://github.com/mvictoras)
|
||||||
|
|
||||||
|
* Allow arbitrary aspect ratios when resizing images via new `ignoreAspectRatio` method.
|
||||||
|
[#192](https://github.com/lovell/sharp/issues/192)
|
||||||
|
[@skedastik](https://github.com/skedastik)
|
||||||
|
|
||||||
|
* Enhance output image contrast by stretching its luminance to cover the full dynamic range via new `normalize` method.
|
||||||
|
[#194](https://github.com/lovell/sharp/issues/194)
|
||||||
|
[@bkw](https://github.com/bkw)
|
||||||
|
[@codingforce](https://github.com/codingforce)
|
||||||
103
docs/index.md
Normal file
@@ -0,0 +1,103 @@
|
|||||||
|
# sharp
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
Resizing an image is typically 4x faster than using
|
||||||
|
the quickest ImageMagick and GraphicsMagick settings.
|
||||||
|
|
||||||
|
[](https://coveralls.io/r/lovell/sharp?branch=master)
|
||||||
|
|
||||||
|
### Formats
|
||||||
|
|
||||||
|
This module supports reading JPEG, PNG, WebP, TIFF, OpenSlide,
|
||||||
|
GIF and other libmagick-supported formats.
|
||||||
|
|
||||||
|
Output images can be in JPEG, PNG and WebP formats as well as uncompressed raw pixel data.
|
||||||
|
|
||||||
|
Streams, Buffer objects and the filesystem can be used for input and output.
|
||||||
|
|
||||||
|
A single input Stream can be split into multiple processing pipelines and output Streams.
|
||||||
|
|
||||||
|
Deep Zoom image pyramids can be generated,
|
||||||
|
suitable for use with "slippy map" tile viewers like
|
||||||
|
[OpenSeadragon](https://github.com/openseadragon/openseadragon)
|
||||||
|
and [Leaflet](https://github.com/turban/Leaflet.Zoomify).
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
As well as image resizing, operations such as
|
||||||
|
rotation, extraction, compositing and gamma correction are available.
|
||||||
|
|
||||||
|
Colour spaces, embedded ICC profiles and alpha transparency channels
|
||||||
|
are all handled correctly.
|
||||||
|
|
||||||
|
### Fast
|
||||||
|
|
||||||
|
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).
|
||||||
|
|
||||||
|
Only small regions of uncompressed image data
|
||||||
|
are held in memory and processed at a time,
|
||||||
|
taking full advantage of multiple CPU cores and L1/L2/L3 cache.
|
||||||
|
|
||||||
|
Everything remains non-blocking thanks to _libuv_,
|
||||||
|
no child processes are spawned and Promises/A+ are supported.
|
||||||
|
|
||||||
|
### Optimal
|
||||||
|
|
||||||
|
Huffman tables are optimised when generating JPEG output images
|
||||||
|
without having to use separate command line tools like
|
||||||
|
[jpegoptim](https://github.com/tjko/jpegoptim) and
|
||||||
|
[jpegtran](http://jpegclub.org/jpegtran/).
|
||||||
|
|
||||||
|
PNG filtering can be disabled,
|
||||||
|
which for diagrams and line art often produces the same result
|
||||||
|
as [pngcrush](http://pmt.sourceforge.net/pngcrush/).
|
||||||
|
|
||||||
|
### Contributing
|
||||||
|
|
||||||
|
A [guide for contributors](https://github.com/lovell/sharp/blob/master/CONTRIBUTING.md)
|
||||||
|
covers reporting bugs, requesting features and submitting code changes.
|
||||||
|
|
||||||
|
### Credits
|
||||||
|
|
||||||
|
This module would never have been possible without
|
||||||
|
the help and code contributions of the following people:
|
||||||
|
|
||||||
|
* [John Cupitt](https://github.com/jcupitt)
|
||||||
|
* [Pierre Inglebert](https://github.com/pierreinglebert)
|
||||||
|
* [Jonathan Ong](https://github.com/jonathanong)
|
||||||
|
* [Chanon Sajjamanochai](https://github.com/chanon)
|
||||||
|
* [Juliano Julio](https://github.com/julianojulio)
|
||||||
|
* [Daniel Gasienica](https://github.com/gasi)
|
||||||
|
* [Julian Walker](https://github.com/julianwa)
|
||||||
|
* [Amit Pitaru](https://github.com/apitaru)
|
||||||
|
* [Brandon Aaron](https://github.com/brandonaaron)
|
||||||
|
* [Andreas Lind](https://github.com/papandreou)
|
||||||
|
* [Maurus Cuelenaere](https://github.com/mcuelenaere)
|
||||||
|
* [Linus Unnebäck](https://github.com/LinusU)
|
||||||
|
* [Victor Mateevitsi](https://github.com/mvictoras)
|
||||||
|
* [Alaric Holloway](https://github.com/skedastik)
|
||||||
|
* [Bernhard K. Weisshuhn](https://github.com/bkw)
|
||||||
|
|
||||||
|
Thank you!
|
||||||
|
|
||||||
|
### Licence
|
||||||
|
|
||||||
|
Copyright 2013, 2014, 2015 Lovell Fuller and contributors.
|
||||||
|
|
||||||
|
Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
you may not use this file except in compliance with the License.
|
||||||
|
You may obtain a copy of the License at
|
||||||
|
[http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0.html)
|
||||||
|
|
||||||
|
Unless required by applicable law or agreed to in writing, software
|
||||||
|
distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
See the License for the specific language governing permissions and
|
||||||
|
limitations under the License.
|
||||||
123
docs/install.md
Normal file
@@ -0,0 +1,123 @@
|
|||||||
|
# Installation
|
||||||
|
|
||||||
|
```sh
|
||||||
|
npm install sharp
|
||||||
|
```
|
||||||
|
|
||||||
|
### Prerequisites
|
||||||
|
|
||||||
|
* Node.js v0.10+ or io.js
|
||||||
|
* [libvips](https://github.com/jcupitt/libvips) v7.40.0+ (7.42.0+ recommended)
|
||||||
|
* C++11 compatible compiler such as gcc 4.6+, clang 3.0+ or MSVC 2013
|
||||||
|
|
||||||
|
### Linux
|
||||||
|
|
||||||
|
[](https://travis-ci.org/lovell/sharp)
|
||||||
|
[](https://snap-ci.com/lovell/sharp/branch/master)
|
||||||
|
|
||||||
|
For a system-wide installation of the most suitable version of
|
||||||
|
libvips and its dependencies on the following Operating Systems:
|
||||||
|
|
||||||
|
* Debian 7, 8
|
||||||
|
* Ubuntu 12.04, 14.04, 14.10, 15.04
|
||||||
|
* Mint 13, 17
|
||||||
|
* RHEL/Centos/Scientific 6, 7
|
||||||
|
* Fedora 21, 22
|
||||||
|
* Amazon Linux 2014.09, 2015.03
|
||||||
|
* OpenSuse 13
|
||||||
|
|
||||||
|
run the following as a user with `sudo` access:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
curl -s https://raw.githubusercontent.com/lovell/sharp/master/preinstall.sh | sudo bash -
|
||||||
|
```
|
||||||
|
|
||||||
|
or run the following as `root`:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
curl -s https://raw.githubusercontent.com/lovell/sharp/master/preinstall.sh | bash -
|
||||||
|
```
|
||||||
|
|
||||||
|
The [preinstall.sh](https://github.com/lovell/sharp/blob/master/preinstall.sh) script requires `curl` and `pkg-config`.
|
||||||
|
|
||||||
|
Add `--with-openslide` to enable OpenSlide support:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
curl -s https://raw.githubusercontent.com/lovell/sharp/master/preinstall.sh | sudo bash -s -- --with-openslide
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Ubuntu LTS
|
||||||
|
|
||||||
|
libvips v7.40.6 is available via a PPA.
|
||||||
|
|
||||||
|
##### 12.04
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo add-apt-repository -y ppa:lovell/precise-backport-vips
|
||||||
|
sudo apt-get update
|
||||||
|
sudo apt-get install -y libvips-dev libgsf-1-dev
|
||||||
|
```
|
||||||
|
|
||||||
|
##### 14.04
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo add-apt-repository -y ppa:lovell/trusty-backport-vips
|
||||||
|
sudo apt-get update
|
||||||
|
sudo apt-get install -y libvips-dev libgsf-1-dev
|
||||||
|
```
|
||||||
|
|
||||||
|
### Mac OS
|
||||||
|
|
||||||
|
[](https://travis-ci.org/lovell/sharp-osx-ci)
|
||||||
|
|
||||||
|
Install libvips via homebrew:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
brew install homebrew/science/vips --with-webp --with-graphicsmagick
|
||||||
|
```
|
||||||
|
|
||||||
|
A missing or incorrectly configured _Xcode Command Line Tools_ installation
|
||||||
|
[can lead](https://github.com/lovell/sharp/issues/80) to a
|
||||||
|
`library not found for -ljpeg` error.
|
||||||
|
If so, please try: `xcode-select --install`.
|
||||||
|
|
||||||
|
The _gettext_ dependency of _libvips_
|
||||||
|
[can lead](https://github.com/lovell/sharp/issues/9)
|
||||||
|
to a `library not found for -lintl` error.
|
||||||
|
If so, please try `brew link gettext --force`.
|
||||||
|
|
||||||
|
### Windows
|
||||||
|
|
||||||
|
[](https://ci.appveyor.com/project/lovell/sharp)
|
||||||
|
|
||||||
|
Requires x86 32-bit Node.js or io.js (use `iojs.exe` rather than `node.exe`).
|
||||||
|
|
||||||
|
The WebP format is currently unsupported.
|
||||||
|
|
||||||
|
1. Ensure the [node-gyp prerequisites](https://github.com/TooTallNate/node-gyp#installation) are met.
|
||||||
|
2. [Download](http://www.vips.ecs.soton.ac.uk/supported/current/win32/) and unzip `vips-dev.x.y.z.zip`.
|
||||||
|
3. Set the `VIPS_HOME` environment variable to the full path of the `vips-dev-x.y.z` directory.
|
||||||
|
4. Add `vips-dev-x.y.z\bin` to `PATH`.
|
||||||
|
|
||||||
|
Versions of MSVC more recent than 2013 may require the use of `npm install --arch=ia32 --msvs_version=2013`.
|
||||||
|
|
||||||
|
### Heroku
|
||||||
|
|
||||||
|
[Alessandro Tagliapietra](https://github.com/alex88) maintains an
|
||||||
|
[Heroku buildpack for libvips](https://github.com/alex88/heroku-buildpack-vips)
|
||||||
|
and its dependencies.
|
||||||
|
|
||||||
|
### Docker
|
||||||
|
|
||||||
|
[Marc Bachmann](https://github.com/marcbachmann) maintains a
|
||||||
|
[Dockerfile for libvips](https://github.com/marcbachmann/dockerfile-libvips).
|
||||||
|
|
||||||
|
```sh
|
||||||
|
docker pull marcbachmann/libvips
|
||||||
|
```
|
||||||
|
|
||||||
|
### Build tools
|
||||||
|
|
||||||
|
* [gulp-responsive](https://www.npmjs.com/package/gulp-responsive)
|
||||||
|
* [gulp-sharp](https://www.npmjs.com/package/gulp-sharp)
|
||||||
|
* [grunt-sharp](https://www.npmjs.com/package/grunt-sharp)
|
||||||
63
docs/performance.md
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
# Performance
|
||||||
|
|
||||||
|
### Test environment
|
||||||
|
|
||||||
|
* AWS EC2 [c4.xlarge](http://aws.amazon.com/ec2/instance-types/#c4)
|
||||||
|
* Ubuntu 15.04
|
||||||
|
* Node.js 0.12.7
|
||||||
|
* libvips 8.0.2
|
||||||
|
* liborc 0.4.22
|
||||||
|
|
||||||
|
### The contenders
|
||||||
|
|
||||||
|
* [lwip](https://www.npmjs.com/package/lwip) 0.0.7 - Wrapper around CImg, compiles dependencies from source
|
||||||
|
* [imagemagick-native](https://www.npmjs.com/package/imagemagick-native) git@45d4e2e - Wrapper around libmagick++, supports Buffers only.
|
||||||
|
* [imagemagick](https://www.npmjs.com/package/imagemagick) 0.1.3 - Supports filesystem only and "*has been unmaintained for a long time*".
|
||||||
|
* [gm](https://www.npmjs.com/package/gm) 1.18.1 - Fully featured wrapper around GraphicsMagick's `convert` command line utility.
|
||||||
|
* sharp 0.11.0 - Caching within libvips disabled to ensure a fair comparison.
|
||||||
|
|
||||||
|
### The task
|
||||||
|
|
||||||
|
Decompress a 2725x2225 JPEG image, resize to 720x480 using bilinear interpolation, then compress to JPEG.
|
||||||
|
|
||||||
|
### Results
|
||||||
|
|
||||||
|
| Module | Input | Output | Ops/sec | Speed-up |
|
||||||
|
| :----------------- | :----- | :----- | ------: | -------: |
|
||||||
|
| lwip | file | file | 1.75 | 1 |
|
||||||
|
| lwip | buffer | buffer | 2.21 | 1.3 |
|
||||||
|
| imagemagick-native | buffer | buffer | 7.13 | 4.1 |
|
||||||
|
| gm | buffer | buffer | 7.27 | 4.2 |
|
||||||
|
| gm | file | file | 7.33 | 4.2 |
|
||||||
|
| imagemagick | file | file | 10.04 | 5.7 |
|
||||||
|
| sharp | stream | stream | 23.12 | 13.2 |
|
||||||
|
| sharp | file | file | 24.43 | 14.0 |
|
||||||
|
| sharp | file | buffer | 24.55 | 14.0 |
|
||||||
|
| sharp | buffer | file | 24.86 | 14.2 |
|
||||||
|
| sharp | buffer | buffer | 24.92 | 14.2 |
|
||||||
|
|
||||||
|
Greater performance can be expected with caching enabled (default) and using 8+ core machines.
|
||||||
|
|
||||||
|
The I/O limits of the relevant (de)compression library will generally determine maximum throughput.
|
||||||
|
|
||||||
|
### Benchmark test prerequisites
|
||||||
|
|
||||||
|
Requires both _ImageMagick_ and _GraphicsMagick_:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
brew install imagemagick
|
||||||
|
brew install graphicsmagick
|
||||||
|
```
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo apt-get install imagemagick graphicsmagick libmagick++-dev
|
||||||
|
```
|
||||||
|
|
||||||
|
### Running the benchmark test
|
||||||
|
|
||||||
|
```sh
|
||||||
|
git clone https://github.com/lovell/sharp.git
|
||||||
|
cd sharp/test/bench
|
||||||
|
npm install
|
||||||
|
npm test
|
||||||
|
```
|
||||||
339
index.js
@@ -3,6 +3,7 @@
|
|||||||
var path = require('path');
|
var path = require('path');
|
||||||
var util = require('util');
|
var util = require('util');
|
||||||
var stream = require('stream');
|
var stream = require('stream');
|
||||||
|
var events = require('events');
|
||||||
|
|
||||||
var semver = require('semver');
|
var semver = require('semver');
|
||||||
var color = require('color');
|
var color = require('color');
|
||||||
@@ -11,6 +12,12 @@ var BluebirdPromise = require('bluebird');
|
|||||||
var sharp = require('./build/Release/sharp');
|
var sharp = require('./build/Release/sharp');
|
||||||
var libvipsVersion = sharp.libvipsVersion();
|
var libvipsVersion = sharp.libvipsVersion();
|
||||||
|
|
||||||
|
var maximum = {
|
||||||
|
width: 0x3FFF,
|
||||||
|
height: 0x3FFF,
|
||||||
|
pixels: Math.pow(0x3FFF, 2)
|
||||||
|
};
|
||||||
|
|
||||||
var Sharp = function(input) {
|
var Sharp = function(input) {
|
||||||
if (!(this instanceof Sharp)) {
|
if (!(this instanceof Sharp)) {
|
||||||
return new Sharp(input);
|
return new Sharp(input);
|
||||||
@@ -21,6 +28,7 @@ var Sharp = function(input) {
|
|||||||
bufferIn: null,
|
bufferIn: null,
|
||||||
streamIn: false,
|
streamIn: false,
|
||||||
sequentialRead: false,
|
sequentialRead: false,
|
||||||
|
limitInputPixels: maximum.pixels,
|
||||||
// ICC profiles
|
// ICC profiles
|
||||||
iccProfilePath: path.join(__dirname, 'icc') + path.sep,
|
iccProfilePath: path.join(__dirname, 'icc') + path.sep,
|
||||||
// resize options
|
// resize options
|
||||||
@@ -34,9 +42,10 @@ var Sharp = function(input) {
|
|||||||
heightPost: -1,
|
heightPost: -1,
|
||||||
width: -1,
|
width: -1,
|
||||||
height: -1,
|
height: -1,
|
||||||
canvas: 'c',
|
canvas: 'crop',
|
||||||
gravity: 0,
|
gravity: 0,
|
||||||
angle: 0,
|
angle: 0,
|
||||||
|
rotateBeforePreExtract: false,
|
||||||
flip: false,
|
flip: false,
|
||||||
flop: false,
|
flop: false,
|
||||||
withoutEnlargement: false,
|
withoutEnlargement: false,
|
||||||
@@ -50,45 +59,56 @@ var Sharp = function(input) {
|
|||||||
sharpenJagged: 2,
|
sharpenJagged: 2,
|
||||||
gamma: 0,
|
gamma: 0,
|
||||||
greyscale: false,
|
greyscale: false,
|
||||||
|
normalize: 0,
|
||||||
|
// overlay
|
||||||
|
overlayPath: '',
|
||||||
// output options
|
// output options
|
||||||
output: '__input',
|
output: '__input',
|
||||||
progressive: false,
|
progressive: false,
|
||||||
quality: 80,
|
quality: 80,
|
||||||
compressionLevel: 6,
|
compressionLevel: 6,
|
||||||
withoutAdaptiveFiltering: false,
|
withoutAdaptiveFiltering: false,
|
||||||
|
withoutChromaSubsampling: false,
|
||||||
|
trellisQuantisation: false,
|
||||||
|
overshootDeringing: false,
|
||||||
|
optimiseScans: false,
|
||||||
streamOut: false,
|
streamOut: false,
|
||||||
withMetadata: false
|
withMetadata: false,
|
||||||
|
withMetadataOrientation: -1,
|
||||||
|
tileSize: 256,
|
||||||
|
tileOverlap: 0,
|
||||||
|
// Function to notify of queue length changes
|
||||||
|
queueListener: function(queueLength) {
|
||||||
|
module.exports.queue.emit('change', queueLength);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
if (typeof input === 'string') {
|
if (typeof input === 'string') {
|
||||||
// input=file
|
// input=file
|
||||||
this.options.fileIn = input;
|
this.options.fileIn = input;
|
||||||
} else if (typeof input === 'object' && input instanceof Buffer) {
|
} else if (typeof input === 'object' && input instanceof Buffer) {
|
||||||
// input=buffer
|
// input=buffer
|
||||||
if (
|
this.options.bufferIn = input;
|
||||||
(input.length > 3) &&
|
} else if (typeof input === 'undefined') {
|
||||||
// JPEG
|
|
||||||
(input[0] === 0xFF && input[1] === 0xD8) ||
|
|
||||||
// PNG
|
|
||||||
(input[0] === 0x89 && input[1] === 0x50) ||
|
|
||||||
// WebP
|
|
||||||
(input[0] === 0x52 && input[1] === 0x49) ||
|
|
||||||
// TIFF
|
|
||||||
(input[0] === 0x4D && input[1] === 0x4D && input[2] === 0x00 && (input[3] === 0x2A || input[3] === 0x2B)) ||
|
|
||||||
(input[0] === 0x49 && input[1] === 0x49 && (input[2] === 0x2A || input[2] === 0x2B) && input[3] === 0x00)
|
|
||||||
) {
|
|
||||||
this.options.bufferIn = input;
|
|
||||||
} else {
|
|
||||||
throw new Error('Buffer contains an unsupported image format. JPEG, PNG, WebP and TIFF are currently supported.');
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// input=stream
|
// input=stream
|
||||||
this.options.streamIn = true;
|
this.options.streamIn = true;
|
||||||
|
} else {
|
||||||
|
throw new Error('Unsupported input ' + typeof input);
|
||||||
}
|
}
|
||||||
return this;
|
return this;
|
||||||
};
|
};
|
||||||
module.exports = Sharp;
|
module.exports = Sharp;
|
||||||
util.inherits(Sharp, stream.Duplex);
|
util.inherits(Sharp, stream.Duplex);
|
||||||
|
|
||||||
|
/*
|
||||||
|
EventEmitter singleton emits queue length 'change' events
|
||||||
|
*/
|
||||||
|
module.exports.queue = new events.EventEmitter();
|
||||||
|
|
||||||
|
/*
|
||||||
|
Supported image formats
|
||||||
|
*/
|
||||||
|
module.exports.format = sharp.format();
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Handle incoming chunk on Writable Stream
|
Handle incoming chunk on Writable Stream
|
||||||
*/
|
*/
|
||||||
@@ -120,7 +140,7 @@ Sharp.prototype._write = function(chunk, encoding, callback) {
|
|||||||
module.exports.gravity = {'center': 0, 'centre': 0, 'north': 1, 'east': 2, 'south': 3, 'west': 4};
|
module.exports.gravity = {'center': 0, 'centre': 0, 'north': 1, 'east': 2, 'south': 3, 'west': 4};
|
||||||
|
|
||||||
Sharp.prototype.crop = function(gravity) {
|
Sharp.prototype.crop = function(gravity) {
|
||||||
this.options.canvas = 'c';
|
this.options.canvas = 'crop';
|
||||||
if (typeof gravity === 'number' && !Number.isNaN(gravity) && gravity >= 0 && gravity <= 4) {
|
if (typeof gravity === 'number' && !Number.isNaN(gravity) && gravity >= 0 && gravity <= 4) {
|
||||||
this.options.gravity = gravity;
|
this.options.gravity = gravity;
|
||||||
} else {
|
} else {
|
||||||
@@ -134,8 +154,16 @@ Sharp.prototype.extract = function(topOffset, leftOffset, width, height) {
|
|||||||
var suffix = this.options.width === -1 && this.options.height === -1 ? 'Pre' : 'Post';
|
var suffix = this.options.width === -1 && this.options.height === -1 ? 'Pre' : 'Post';
|
||||||
var values = arguments;
|
var values = arguments;
|
||||||
['topOffset', 'leftOffset', 'width', 'height'].forEach(function(name, index) {
|
['topOffset', 'leftOffset', 'width', 'height'].forEach(function(name, index) {
|
||||||
this.options[name + suffix] = values[index];
|
if (typeof values[index] === 'number' && !Number.isNaN(values[index]) && (values[index] % 1 === 0) && values[index] >= 0) {
|
||||||
|
this.options[name + suffix] = values[index];
|
||||||
|
} else {
|
||||||
|
throw new Error('Non-integer value for ' + name + ' of ' + values[index]);
|
||||||
|
}
|
||||||
}.bind(this));
|
}.bind(this));
|
||||||
|
// Ensure existing rotation occurs before pre-resize extraction
|
||||||
|
if (suffix === 'Pre' && this.options.angle !== 0) {
|
||||||
|
this.options.rotateBeforePreExtract = true;
|
||||||
|
}
|
||||||
return this;
|
return this;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -152,12 +180,26 @@ Sharp.prototype.background = function(rgba) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
Sharp.prototype.embed = function() {
|
Sharp.prototype.embed = function() {
|
||||||
this.options.canvas = 'e';
|
this.options.canvas = 'embed';
|
||||||
return this;
|
return this;
|
||||||
};
|
};
|
||||||
|
|
||||||
Sharp.prototype.max = function() {
|
Sharp.prototype.max = function() {
|
||||||
this.options.canvas = 'm';
|
this.options.canvas = 'max';
|
||||||
|
return this;
|
||||||
|
};
|
||||||
|
|
||||||
|
Sharp.prototype.min = function() {
|
||||||
|
this.options.canvas = 'min';
|
||||||
|
return this;
|
||||||
|
};
|
||||||
|
|
||||||
|
/*
|
||||||
|
Ignoring the aspect ratio of the input, stretch the image to
|
||||||
|
the exact width and/or height provided via the resize method.
|
||||||
|
*/
|
||||||
|
Sharp.prototype.ignoreAspectRatio = function() {
|
||||||
|
this.options.canvas = 'ignore_aspect';
|
||||||
return this;
|
return this;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -166,6 +208,17 @@ Sharp.prototype.flatten = function(flatten) {
|
|||||||
return this;
|
return this;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
Sharp.prototype.overlayWith = function(overlayPath) {
|
||||||
|
if (typeof overlayPath !== 'string') {
|
||||||
|
throw new Error('The overlay path must be a string');
|
||||||
|
}
|
||||||
|
if (overlayPath === '') {
|
||||||
|
throw new Error('The overlay path cannot be empty');
|
||||||
|
}
|
||||||
|
this.options.overlayPath = overlayPath;
|
||||||
|
return this;
|
||||||
|
};
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Rotate output image by 0, 90, 180 or 270 degrees
|
Rotate output image by 0, 90, 180 or 270 degrees
|
||||||
Auto-rotation based on the EXIF Orientation tag is represented by an angle of -1
|
Auto-rotation based on the EXIF Orientation tag is represented by an angle of -1
|
||||||
@@ -280,7 +333,18 @@ module.exports.interpolator = {
|
|||||||
vertexSplitQuadraticBasisSpline: 'vsqbs'
|
vertexSplitQuadraticBasisSpline: 'vsqbs'
|
||||||
};
|
};
|
||||||
Sharp.prototype.interpolateWith = function(interpolator) {
|
Sharp.prototype.interpolateWith = function(interpolator) {
|
||||||
this.options.interpolator = interpolator;
|
var isValid = false;
|
||||||
|
for (var key in module.exports.interpolator) {
|
||||||
|
if (module.exports.interpolator[key] === interpolator) {
|
||||||
|
isValid = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (isValid) {
|
||||||
|
this.options.interpolator = interpolator;
|
||||||
|
} else {
|
||||||
|
throw new Error('Invalid interpolator ' + interpolator);
|
||||||
|
}
|
||||||
return this;
|
return this;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -300,6 +364,19 @@ Sharp.prototype.gamma = function(gamma) {
|
|||||||
return this;
|
return this;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/*
|
||||||
|
Enhance output image contrast by stretching its luminance to cover the full dynamic range
|
||||||
|
*/
|
||||||
|
Sharp.prototype.normalize = function(normalize) {
|
||||||
|
if (process.platform !== 'win32') {
|
||||||
|
this.options.normalize = (typeof normalize === 'boolean') ? normalize : true;
|
||||||
|
} else {
|
||||||
|
console.error('normalize unavailable on win32 platform');
|
||||||
|
}
|
||||||
|
return this;
|
||||||
|
};
|
||||||
|
Sharp.prototype.normalise = Sharp.prototype.normalize;
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Convert to greyscale
|
Convert to greyscale
|
||||||
*/
|
*/
|
||||||
@@ -320,7 +397,7 @@ Sharp.prototype.sequentialRead = function(sequentialRead) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
Sharp.prototype.quality = function(quality) {
|
Sharp.prototype.quality = function(quality) {
|
||||||
if (!Number.isNaN(quality) && quality >= 1 && quality <= 100) {
|
if (!Number.isNaN(quality) && quality >= 1 && quality <= 100 && quality % 1 === 0) {
|
||||||
this.options.quality = quality;
|
this.options.quality = quality;
|
||||||
} else {
|
} else {
|
||||||
throw new Error('Invalid quality (1 to 100) ' + quality);
|
throw new Error('Invalid quality (1 to 100) ' + quality);
|
||||||
@@ -341,10 +418,10 @@ Sharp.prototype.compressionLevel = function(compressionLevel) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Disable the use of adaptive row filtering for PNG output - requires libvips 7.41.0+
|
Disable the use of adaptive row filtering for PNG output - requires libvips 7.42.0+
|
||||||
*/
|
*/
|
||||||
Sharp.prototype.withoutAdaptiveFiltering = function(withoutAdaptiveFiltering) {
|
Sharp.prototype.withoutAdaptiveFiltering = function(withoutAdaptiveFiltering) {
|
||||||
if (semver.gte(libvipsVersion, '7.41.0')) {
|
if (semver.gte(libvipsVersion, '7.42.0')) {
|
||||||
this.options.withoutAdaptiveFiltering = (typeof withoutAdaptiveFiltering === 'boolean') ? withoutAdaptiveFiltering : true;
|
this.options.withoutAdaptiveFiltering = (typeof withoutAdaptiveFiltering === 'boolean') ? withoutAdaptiveFiltering : true;
|
||||||
} else {
|
} else {
|
||||||
console.error('withoutAdaptiveFiltering requires libvips 7.41.0+');
|
console.error('withoutAdaptiveFiltering requires libvips 7.41.0+');
|
||||||
@@ -352,8 +429,103 @@ Sharp.prototype.withoutAdaptiveFiltering = function(withoutAdaptiveFiltering) {
|
|||||||
return this;
|
return this;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/*
|
||||||
|
Disable the use of chroma subsampling for JPEG output
|
||||||
|
*/
|
||||||
|
Sharp.prototype.withoutChromaSubsampling = function(withoutChromaSubsampling) {
|
||||||
|
this.options.withoutChromaSubsampling = (typeof withoutChromaSubsampling === 'boolean') ? withoutChromaSubsampling : true;
|
||||||
|
return this;
|
||||||
|
};
|
||||||
|
|
||||||
|
/*
|
||||||
|
Apply trellis quantisation to JPEG output - requires libvips 8.0.0+ compiled against mozjpeg 3.0+
|
||||||
|
*/
|
||||||
|
Sharp.prototype.trellisQuantisation = function(trellisQuantisation) {
|
||||||
|
if (semver.gte(libvipsVersion, '8.0.0')) {
|
||||||
|
this.options.trellisQuantisation = (typeof trellisQuantisation === 'boolean') ? trellisQuantisation : true;
|
||||||
|
} else {
|
||||||
|
console.error('trellisQuantisation requires libvips 8.0.0+');
|
||||||
|
}
|
||||||
|
return this;
|
||||||
|
};
|
||||||
|
Sharp.prototype.trellisQuantization = Sharp.prototype.trellisQuantisation;
|
||||||
|
|
||||||
|
/*
|
||||||
|
Apply overshoot deringing to JPEG output - requires libvips 8.0.0+ compiled against mozjpeg 3.0+
|
||||||
|
*/
|
||||||
|
Sharp.prototype.overshootDeringing = function(overshootDeringing) {
|
||||||
|
if (semver.gte(libvipsVersion, '8.0.0')) {
|
||||||
|
this.options.overshootDeringing = (typeof overshootDeringing === 'boolean') ? overshootDeringing : true;
|
||||||
|
} else {
|
||||||
|
console.error('overshootDeringing requires libvips 8.0.0+');
|
||||||
|
}
|
||||||
|
return this;
|
||||||
|
};
|
||||||
|
|
||||||
|
/*
|
||||||
|
Optimise scans in progressive JPEG output - requires libvips 8.0.0+ compiled against mozjpeg 3.0+
|
||||||
|
*/
|
||||||
|
Sharp.prototype.optimiseScans = function(optimiseScans) {
|
||||||
|
if (semver.gte(libvipsVersion, '8.0.0')) {
|
||||||
|
this.options.optimiseScans = (typeof optimiseScans === 'boolean') ? optimiseScans : true;
|
||||||
|
if (this.options.optimiseScans) {
|
||||||
|
this.progressive();
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
console.error('optimiseScans requires libvips 8.0.0+');
|
||||||
|
}
|
||||||
|
return this;
|
||||||
|
};
|
||||||
|
Sharp.prototype.optimizeScans = Sharp.prototype.optimiseScans;
|
||||||
|
|
||||||
|
/*
|
||||||
|
Include all metadata (EXIF, XMP, IPTC) from the input image in the output image
|
||||||
|
Optionally provide an Object with attributes to update:
|
||||||
|
orientation: numeric value for EXIF Orientation tag
|
||||||
|
*/
|
||||||
Sharp.prototype.withMetadata = function(withMetadata) {
|
Sharp.prototype.withMetadata = function(withMetadata) {
|
||||||
this.options.withMetadata = (typeof withMetadata === 'boolean') ? withMetadata : true;
|
this.options.withMetadata = (typeof withMetadata === 'boolean') ? withMetadata : true;
|
||||||
|
if (typeof withMetadata === 'object') {
|
||||||
|
if ('orientation' in withMetadata) {
|
||||||
|
if (
|
||||||
|
typeof withMetadata.orientation === 'number' &&
|
||||||
|
!Number.isNaN(withMetadata.orientation) &&
|
||||||
|
withMetadata.orientation % 1 === 0 &&
|
||||||
|
withMetadata.orientation >=0 &&
|
||||||
|
withMetadata.orientation <= 7
|
||||||
|
) {
|
||||||
|
this.options.withMetadataOrientation = withMetadata.orientation;
|
||||||
|
} else {
|
||||||
|
throw new Error('Invalid orientation (0 to 7) ' + withMetadata.orientation);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return this;
|
||||||
|
};
|
||||||
|
|
||||||
|
/*
|
||||||
|
Tile size and overlap for Deep Zoom output
|
||||||
|
*/
|
||||||
|
Sharp.prototype.tile = function(size, overlap) {
|
||||||
|
// Size of square tiles, in pixels
|
||||||
|
if (typeof size !== 'undefined' && size !== null) {
|
||||||
|
if (!Number.isNaN(size) && size % 1 === 0 && size >= 1 && size <= 8192) {
|
||||||
|
this.options.tileSize = size;
|
||||||
|
} else {
|
||||||
|
throw new Error('Invalid tile size (1 to 8192) ' + size);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Overlap of tiles, in pixels
|
||||||
|
if (typeof overlap !== 'undefined' && overlap !== null) {
|
||||||
|
if (!Number.isNaN(overlap) && overlap % 1 === 0 && overlap >=0 && overlap <= 8192) {
|
||||||
|
if (overlap > this.options.tileSize) {
|
||||||
|
throw new Error('Tile overlap ' + overlap + ' cannot be larger than tile size ' + this.options.tileSize);
|
||||||
|
}
|
||||||
|
this.options.tileOverlap = overlap;
|
||||||
|
} else {
|
||||||
|
throw new Error('Invalid tile overlap (0 to 8192) ' + overlap);
|
||||||
|
}
|
||||||
|
}
|
||||||
return this;
|
return this;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -361,24 +533,37 @@ Sharp.prototype.resize = function(width, height) {
|
|||||||
if (!width) {
|
if (!width) {
|
||||||
this.options.width = -1;
|
this.options.width = -1;
|
||||||
} else {
|
} else {
|
||||||
if (typeof width === 'number' && !Number.isNaN(width)) {
|
if (typeof width === 'number' && !Number.isNaN(width) && width % 1 === 0 && width > 0 && width <= maximum.width) {
|
||||||
this.options.width = width;
|
this.options.width = width;
|
||||||
} else {
|
} else {
|
||||||
throw new Error('Invalid width ' + width);
|
throw new Error('Invalid width (1 to ' + maximum.width + ') ' + width);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (!height) {
|
if (!height) {
|
||||||
this.options.height = -1;
|
this.options.height = -1;
|
||||||
} else {
|
} else {
|
||||||
if (typeof height === 'number' && !Number.isNaN(height)) {
|
if (typeof height === 'number' && !Number.isNaN(height) && height % 1 === 0 && height > 0 && height <= maximum.height) {
|
||||||
this.options.height = height;
|
this.options.height = height;
|
||||||
} else {
|
} else {
|
||||||
throw new Error('Invalid height ' + height);
|
throw new Error('Invalid height (1 to ' + maximum.height + ') ' + height);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return this;
|
return this;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/*
|
||||||
|
Limit the total number of pixels for input images
|
||||||
|
Assumes the image dimensions contained in the file header can be trusted
|
||||||
|
*/
|
||||||
|
Sharp.prototype.limitInputPixels = function(limit) {
|
||||||
|
if (typeof limit === 'number' && !Number.isNaN(limit) && limit % 1 === 0 && limit > 0) {
|
||||||
|
this.options.limitInputPixels = limit;
|
||||||
|
} else {
|
||||||
|
throw new Error('Invalid pixel limit (1 to ' + maximum.pixels + ') ' + limit);
|
||||||
|
}
|
||||||
|
return this;
|
||||||
|
};
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Write output image data to a file
|
Write output image data to a file
|
||||||
*/
|
*/
|
||||||
@@ -400,38 +585,80 @@ Sharp.prototype.toFile = function(output, callback) {
|
|||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
this.options.output = output;
|
this.options.output = output;
|
||||||
return this._sharp(callback);
|
return this._pipeline(callback);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return this;
|
return this;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/*
|
||||||
|
Write output to a Buffer
|
||||||
|
*/
|
||||||
Sharp.prototype.toBuffer = function(callback) {
|
Sharp.prototype.toBuffer = function(callback) {
|
||||||
return this._sharp(callback);
|
return this._pipeline(callback);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/*
|
||||||
|
Force JPEG output
|
||||||
|
*/
|
||||||
Sharp.prototype.jpeg = function() {
|
Sharp.prototype.jpeg = function() {
|
||||||
this.options.output = '__jpeg';
|
this.options.output = '__jpeg';
|
||||||
return this;
|
return this;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/*
|
||||||
|
Force PNG output
|
||||||
|
*/
|
||||||
Sharp.prototype.png = function() {
|
Sharp.prototype.png = function() {
|
||||||
this.options.output = '__png';
|
this.options.output = '__png';
|
||||||
return this;
|
return this;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/*
|
||||||
|
Force WebP output
|
||||||
|
*/
|
||||||
Sharp.prototype.webp = function() {
|
Sharp.prototype.webp = function() {
|
||||||
this.options.output = '__webp';
|
this.options.output = '__webp';
|
||||||
return this;
|
return this;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/*
|
||||||
|
Force raw, uint8 output
|
||||||
|
*/
|
||||||
|
Sharp.prototype.raw = function() {
|
||||||
|
var supportsRawOutput = module.exports.format.raw.output;
|
||||||
|
if (supportsRawOutput.file || supportsRawOutput.buffer || supportsRawOutput.stream) {
|
||||||
|
this.options.output = '__raw';
|
||||||
|
} else {
|
||||||
|
console.error('Raw output requires libvips 7.42.0+');
|
||||||
|
}
|
||||||
|
return this;
|
||||||
|
};
|
||||||
|
|
||||||
|
/*
|
||||||
|
Force output to a given format
|
||||||
|
@param format is either the id as a String or an Object with an 'id' attribute
|
||||||
|
*/
|
||||||
|
Sharp.prototype.toFormat = function(format) {
|
||||||
|
var id = format;
|
||||||
|
if (typeof format === 'object') {
|
||||||
|
id = format.id;
|
||||||
|
}
|
||||||
|
if (typeof id === 'string' && typeof module.exports.format[id] === 'object' && typeof this[id] === 'function') {
|
||||||
|
this[id]();
|
||||||
|
} else {
|
||||||
|
throw new Error('Unsupported format ' + format);
|
||||||
|
}
|
||||||
|
return this;
|
||||||
|
};
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Used by a Writable Stream to notify that it is ready for data
|
Used by a Writable Stream to notify that it is ready for data
|
||||||
*/
|
*/
|
||||||
Sharp.prototype._read = function() {
|
Sharp.prototype._read = function() {
|
||||||
if (!this.options.streamOut) {
|
if (!this.options.streamOut) {
|
||||||
this.options.streamOut = true;
|
this.options.streamOut = true;
|
||||||
this._sharp();
|
this._pipeline();
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -439,18 +666,18 @@ Sharp.prototype._read = function() {
|
|||||||
Invoke the C++ image processing pipeline
|
Invoke the C++ image processing pipeline
|
||||||
Supports callback, stream and promise variants
|
Supports callback, stream and promise variants
|
||||||
*/
|
*/
|
||||||
Sharp.prototype._sharp = function(callback) {
|
Sharp.prototype._pipeline = function(callback) {
|
||||||
var that = this;
|
var that = this;
|
||||||
if (typeof callback === 'function') {
|
if (typeof callback === 'function') {
|
||||||
// output=file/buffer
|
// output=file/buffer
|
||||||
if (this.options.streamIn) {
|
if (this.options.streamIn) {
|
||||||
// output=file/buffer, input=stream
|
// output=file/buffer, input=stream
|
||||||
this.on('finish', function() {
|
this.on('finish', function() {
|
||||||
sharp.resize(that.options, callback);
|
sharp.pipeline(that.options, callback);
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
// output=file/buffer, input=file/buffer
|
// output=file/buffer, input=file/buffer
|
||||||
sharp.resize(this.options, callback);
|
sharp.pipeline(this.options, callback);
|
||||||
}
|
}
|
||||||
return this;
|
return this;
|
||||||
} else if (this.options.streamOut) {
|
} else if (this.options.streamOut) {
|
||||||
@@ -458,9 +685,9 @@ Sharp.prototype._sharp = function(callback) {
|
|||||||
if (this.options.streamIn) {
|
if (this.options.streamIn) {
|
||||||
// output=stream, input=stream
|
// output=stream, input=stream
|
||||||
this.on('finish', function() {
|
this.on('finish', function() {
|
||||||
sharp.resize(that.options, function(err, data) {
|
sharp.pipeline(that.options, function(err, data) {
|
||||||
if (err) {
|
if (err) {
|
||||||
that.emit('error', new Error(err));
|
that.emit('error', err);
|
||||||
} else {
|
} else {
|
||||||
that.push(data);
|
that.push(data);
|
||||||
}
|
}
|
||||||
@@ -469,9 +696,9 @@ Sharp.prototype._sharp = function(callback) {
|
|||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
// output=stream, input=file/buffer
|
// output=stream, input=file/buffer
|
||||||
sharp.resize(this.options, function(err, data) {
|
sharp.pipeline(this.options, function(err, data) {
|
||||||
if (err) {
|
if (err) {
|
||||||
that.emit('error', new Error(err));
|
that.emit('error', err);
|
||||||
} else {
|
} else {
|
||||||
that.push(data);
|
that.push(data);
|
||||||
}
|
}
|
||||||
@@ -485,7 +712,7 @@ Sharp.prototype._sharp = function(callback) {
|
|||||||
// output=promise, input=stream
|
// output=promise, input=stream
|
||||||
return new BluebirdPromise(function(resolve, reject) {
|
return new BluebirdPromise(function(resolve, reject) {
|
||||||
that.on('finish', function() {
|
that.on('finish', function() {
|
||||||
sharp.resize(that.options, function(err, data) {
|
sharp.pipeline(that.options, function(err, data) {
|
||||||
if (err) {
|
if (err) {
|
||||||
reject(err);
|
reject(err);
|
||||||
} else {
|
} else {
|
||||||
@@ -497,7 +724,7 @@ Sharp.prototype._sharp = function(callback) {
|
|||||||
} else {
|
} else {
|
||||||
// output=promise, input=file/buffer
|
// output=promise, input=file/buffer
|
||||||
return new BluebirdPromise(function(resolve, reject) {
|
return new BluebirdPromise(function(resolve, reject) {
|
||||||
sharp.resize(that.options, function(err, data) {
|
sharp.pipeline(that.options, function(err, data) {
|
||||||
if (err) {
|
if (err) {
|
||||||
reject(err);
|
reject(err);
|
||||||
} else {
|
} else {
|
||||||
@@ -528,22 +755,22 @@ Sharp.prototype.metadata = function(callback) {
|
|||||||
if (this.options.streamIn) {
|
if (this.options.streamIn) {
|
||||||
return new BluebirdPromise(function(resolve, reject) {
|
return new BluebirdPromise(function(resolve, reject) {
|
||||||
that.on('finish', function() {
|
that.on('finish', function() {
|
||||||
sharp.metadata(that.options, function(err, data) {
|
sharp.metadata(that.options, function(err, metadata) {
|
||||||
if (err) {
|
if (err) {
|
||||||
reject(err);
|
reject(err);
|
||||||
} else {
|
} else {
|
||||||
resolve(data);
|
resolve(metadata);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
return new BluebirdPromise(function(resolve, reject) {
|
return new BluebirdPromise(function(resolve, reject) {
|
||||||
sharp.metadata(that.options, function(err, data) {
|
sharp.metadata(that.options, function(err, metadata) {
|
||||||
if (err) {
|
if (err) {
|
||||||
reject(err);
|
reject(err);
|
||||||
} else {
|
} else {
|
||||||
resolve(data);
|
resolve(metadata);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -551,6 +778,24 @@ Sharp.prototype.metadata = function(callback) {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/*
|
||||||
|
Clone new instance using existing options.
|
||||||
|
Cloned instances share the same input.
|
||||||
|
*/
|
||||||
|
Sharp.prototype.clone = function() {
|
||||||
|
// Clone existing options
|
||||||
|
var clone = new Sharp();
|
||||||
|
util._extend(clone.options, this.options);
|
||||||
|
clone.streamIn = false;
|
||||||
|
// Pass 'finish' event to clone for Stream-based input
|
||||||
|
this.on('finish', function() {
|
||||||
|
// Clone inherits input data
|
||||||
|
clone.options.bufferIn = this.options.bufferIn;
|
||||||
|
clone.emit('finish');
|
||||||
|
});
|
||||||
|
return clone;
|
||||||
|
};
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Get and set cache memory and item limits
|
Get and set cache memory and item limits
|
||||||
*/
|
*/
|
||||||
|
|||||||
17
mkdocs.yml
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
site_name: sharp
|
||||||
|
site_url: http://sharp.dimens.io/
|
||||||
|
repo_url: https://github.com/lovell/sharp
|
||||||
|
site_description: The fastest Node.js module for resizing JPEG, PNG, WebP and TIFF images. Uses the libvips library.
|
||||||
|
copyright: <a href="https://dimens.io/">dimens.io</a>
|
||||||
|
google_analytics: ['UA-13034748-12', 'sharp.dimens.io']
|
||||||
|
theme: readthedocs
|
||||||
|
markdown_extensions:
|
||||||
|
- toc:
|
||||||
|
permalink: True
|
||||||
|
dev_addr: 0.0.0.0:10101
|
||||||
|
pages:
|
||||||
|
- Home: index.md
|
||||||
|
- Installation: install.md
|
||||||
|
- API: api.md
|
||||||
|
- Performance: performance.md
|
||||||
|
- Changelog: changelog.md
|
||||||
40
package.json
Executable file → Normal file
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "sharp",
|
"name": "sharp",
|
||||||
"version": "0.8.4",
|
"version": "0.11.1",
|
||||||
"author": "Lovell Fuller <npm@lovell.info>",
|
"author": "Lovell Fuller <npm@lovell.info>",
|
||||||
"contributors": [
|
"contributors": [
|
||||||
"Pierre Inglebert <pierre.inglebert@gmail.com>",
|
"Pierre Inglebert <pierre.inglebert@gmail.com>",
|
||||||
@@ -11,11 +11,21 @@
|
|||||||
"Julian Walker <julian@fiftythree.com>",
|
"Julian Walker <julian@fiftythree.com>",
|
||||||
"Amit Pitaru <pitaru.amit@gmail.com>",
|
"Amit Pitaru <pitaru.amit@gmail.com>",
|
||||||
"Brandon Aaron <hello.brandon@aaron.sh>",
|
"Brandon Aaron <hello.brandon@aaron.sh>",
|
||||||
"Andreas Lind <andreas@one.com>"
|
"Andreas Lind <andreas@one.com>",
|
||||||
|
"Maurus Cuelenaere <mcuelenaere@gmail.com>",
|
||||||
|
"Linus Unnebäck <linus@folkdatorn.se>",
|
||||||
|
"Victor Mateevitsi <mvictoras@gmail.com>",
|
||||||
|
"Alaric Holloway <alaric.holloway@gmail.com>",
|
||||||
|
"Bernhard K. Weisshuhn <bkw@codingforce.com>"
|
||||||
],
|
],
|
||||||
"description": "High performance Node.js module to resize JPEG, PNG, WebP and TIFF images using the libvips library",
|
"description": "High performance Node.js module to resize JPEG, PNG, WebP and TIFF images using the libvips library",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"test": "node ./node_modules/istanbul/lib/cli.js cover ./node_modules/mocha/bin/_mocha -- --slow=5000 --timeout=10000 ./test/unit/*.js"
|
"clean": "rm -rf test/fixtures/output.*",
|
||||||
|
"test": "VIPS_WARNING=0 node ./node_modules/istanbul/lib/cli.js cover ./node_modules/mocha/bin/_mocha -- --slow=5000 --timeout=20000 ./test/unit/*.js",
|
||||||
|
"test-clean": "npm run clean && npm install && npm test",
|
||||||
|
"test-leak": "cd test/leak; ./leak.sh; cd - > /dev/null",
|
||||||
|
"test-win32-node": "node ./node_modules/mocha/bin/mocha --slow=5000 --timeout=30000 ./test/unit/*.js",
|
||||||
|
"test-win32-iojs": "iojs ./node_modules/mocha/bin/mocha --slow=5000 --timeout=30000 ./test/unit/*.js"
|
||||||
},
|
},
|
||||||
"main": "index.js",
|
"main": "index.js",
|
||||||
"repository": {
|
"repository": {
|
||||||
@@ -27,6 +37,7 @@
|
|||||||
"png",
|
"png",
|
||||||
"webp",
|
"webp",
|
||||||
"tiff",
|
"tiff",
|
||||||
|
"dzi",
|
||||||
"resize",
|
"resize",
|
||||||
"thumbnail",
|
"thumbnail",
|
||||||
"crop",
|
"crop",
|
||||||
@@ -34,18 +45,23 @@
|
|||||||
"vips"
|
"vips"
|
||||||
],
|
],
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"bluebird": "^2.6.4",
|
"bluebird": "^2.9.33",
|
||||||
"color": "^0.7.3",
|
"color": "^0.10.1",
|
||||||
"nan": "^1.5.1",
|
"nan": "^1.8.4",
|
||||||
"semver": "^4.1.0"
|
"semver": "^5.0.1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"mocha": "^2.0.1",
|
"async": "^1.4.2",
|
||||||
"mocha-jshint": "^0.0.9",
|
"coveralls": "^2.11.2",
|
||||||
"istanbul": "^0.3.5",
|
"exif-reader": "1.0.0",
|
||||||
"coveralls": "^2.11.2"
|
"icc": "^0.0.2",
|
||||||
|
"istanbul": "^0.3.17",
|
||||||
|
"mocha": "^2.2.5",
|
||||||
|
"mocha-jshint": "^2.2.3",
|
||||||
|
"node-cpplint": "^0.4.0",
|
||||||
|
"rimraf": "^2.4.1"
|
||||||
},
|
},
|
||||||
"license": "Apache 2.0",
|
"license": "Apache-2.0",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=0.10"
|
"node": ">=0.10"
|
||||||
}
|
}
|
||||||
|
|||||||
405
preinstall.sh
@@ -2,7 +2,6 @@
|
|||||||
|
|
||||||
# Ensures libvips is installed and attempts to install it if not
|
# Ensures libvips is installed and attempts to install it if not
|
||||||
# Currently supports:
|
# Currently supports:
|
||||||
# * Mac OS
|
|
||||||
# * Debian Linux
|
# * Debian Linux
|
||||||
# * Debian 7, 8
|
# * Debian 7, 8
|
||||||
# * Ubuntu 12.04, 14.04, 14.10, 15.04
|
# * Ubuntu 12.04, 14.04, 14.10, 15.04
|
||||||
@@ -10,53 +9,106 @@
|
|||||||
# * Red Hat Linux
|
# * Red Hat Linux
|
||||||
# * RHEL/Centos/Scientific 6, 7
|
# * RHEL/Centos/Scientific 6, 7
|
||||||
# * Fedora 21, 22
|
# * Fedora 21, 22
|
||||||
# * Amazon Linux 2014.09
|
# * Amazon Linux 2014.09, 2015.03
|
||||||
|
|
||||||
vips_version_minimum=7.40.0
|
vips_version_minimum=7.40.0
|
||||||
vips_version_latest_major=7.42
|
vips_version_latest_major_minor=8.0
|
||||||
vips_version_latest_minor=0
|
vips_version_latest_patch=2
|
||||||
|
|
||||||
|
openslide_version_minimum=3.4.0
|
||||||
|
openslide_version_latest_major_minor=3.4
|
||||||
|
openslide_version_latest_patch=1
|
||||||
|
|
||||||
install_libvips_from_source() {
|
install_libvips_from_source() {
|
||||||
echo "Compiling libvips $vips_version_latest_major.$vips_version_latest_minor from source"
|
echo "Compiling libvips $vips_version_latest_major_minor.$vips_version_latest_patch from source"
|
||||||
curl -O http://www.vips.ecs.soton.ac.uk/supported/$vips_version_latest_major/vips-$vips_version_latest_major.$vips_version_latest_minor.tar.gz
|
curl -O http://www.vips.ecs.soton.ac.uk/supported/$vips_version_latest_major_minor/vips-$vips_version_latest_major_minor.$vips_version_latest_patch.tar.gz
|
||||||
tar zvxf vips-$vips_version_latest_major.$vips_version_latest_minor.tar.gz
|
tar zvxf vips-$vips_version_latest_major_minor.$vips_version_latest_patch.tar.gz
|
||||||
cd vips-$vips_version_latest_major.$vips_version_latest_minor
|
cd vips-$vips_version_latest_major_minor.$vips_version_latest_patch
|
||||||
./configure --enable-debug=no --enable-docs=no --enable-cxx=yes --without-python --without-orc --without-fftw --without-gsf $1
|
./configure --disable-debug --disable-docs --disable-static --disable-introspection --enable-cxx=yes --without-python --without-orc --without-fftw $1
|
||||||
make
|
make
|
||||||
make install
|
make install
|
||||||
cd ..
|
cd ..
|
||||||
rm -rf vips-$vips_version_latest_major.$vips_version_latest_minor
|
rm -rf vips-$vips_version_latest_major_minor.$vips_version_latest_patch
|
||||||
rm vips-$vips_version_latest_major.$vips_version_latest_minor.tar.gz
|
rm vips-$vips_version_latest_major_minor.$vips_version_latest_patch.tar.gz
|
||||||
ldconfig
|
ldconfig
|
||||||
echo "Installed libvips $vips_version_latest_major.$vips_version_latest_minor"
|
echo "Installed libvips $vips_version_latest_major_minor.$vips_version_latest_patch"
|
||||||
|
}
|
||||||
|
|
||||||
|
install_libopenslide_from_source() {
|
||||||
|
echo "Compiling openslide $openslide_version_latest_major_minor.$openslide_version_latest_patch from source"
|
||||||
|
curl -O -L https://github.com/openslide/openslide/releases/download/v$openslide_version_latest_major_minor.$openslide_version_latest_patch/openslide-$openslide_version_latest_major_minor.$openslide_version_latest_patch.tar.gz
|
||||||
|
tar xzvf openslide-$openslide_version_latest_major_minor.$openslide_version_latest_patch.tar.gz
|
||||||
|
cd openslide-$openslide_version_latest_major_minor.$openslide_version_latest_patch
|
||||||
|
PKG_CONFIG_PATH=$pkg_config_path ./configure $1
|
||||||
|
make
|
||||||
|
make install
|
||||||
|
cd ..
|
||||||
|
rm -rf openslide-$openslide_version_latest_major_minor.$openslide_version_latest_patch
|
||||||
|
rm openslide-$openslide_version_latest_major_minor.$openslide_version_latest_patch.tar.gz
|
||||||
|
ldconfig
|
||||||
|
echo "Installed libopenslide $openslide_version_latest_major_minor.$openslide_version_latest_patch"
|
||||||
}
|
}
|
||||||
|
|
||||||
sorry() {
|
sorry() {
|
||||||
echo "Sorry, I don't yet know how to install libvips on $1"
|
echo "Sorry, I don't yet know how to install lib$1 on $2"
|
||||||
exit 1
|
exit 1
|
||||||
}
|
}
|
||||||
|
|
||||||
# Is libvips already installed, and is it at least the minimum required version?
|
pkg_config_path="$PKG_CONFIG_PATH:/usr/local/lib/pkgconfig:/usr/lib/pkgconfig"
|
||||||
|
|
||||||
if ! type pkg-config >/dev/null; then
|
check_if_library_exists() {
|
||||||
sorry "a system without pkg-config"
|
PKG_CONFIG_PATH=$pkg_config_path pkg-config --exists $1
|
||||||
|
if [ $? -eq 0 ]; then
|
||||||
|
version_found=$(PKG_CONFIG_PATH=$pkg_config_path pkg-config --modversion $1)
|
||||||
|
PKG_CONFIG_PATH=$pkg_config_path pkg-config --atleast-version=$2 $1
|
||||||
|
if [ $? -eq 0 ]; then
|
||||||
|
# Found suitable version of libvips
|
||||||
|
echo "Found lib$1 $version_found"
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
echo "Found lib$1 $version_found but require $2"
|
||||||
|
else
|
||||||
|
echo "Could not find lib$1 using a PKG_CONFIG_PATH of '$pkg_config_path'"
|
||||||
|
fi
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
enable_openslide=0
|
||||||
|
# Is libvips already installed, and is it at least the minimum required version?
|
||||||
|
if [ $# -eq 1 ]; then
|
||||||
|
if [ "$1" = "--with-openslide" ]; then
|
||||||
|
echo "Installing vips with openslide support"
|
||||||
|
enable_openslide=1
|
||||||
|
else
|
||||||
|
echo "Sorry, $1 is not supported. Did you mean --with-openslide?"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
fi
|
fi
|
||||||
|
|
||||||
pkg_config_path_homebrew=`which brew >/dev/null 2>&1 && eval $(brew --env) && echo $PKG_CONFIG_LIBDIR || true`
|
if ! type pkg-config >/dev/null; then
|
||||||
pkg_config_path="$pkg_config_path_homebrew:$PKG_CONFIG_PATH:/usr/local/lib/pkgconfig:/usr/lib/pkgconfig"
|
sorry "vips" "a system without pkg-config"
|
||||||
|
fi
|
||||||
|
|
||||||
PKG_CONFIG_PATH=$pkg_config_path pkg-config --exists vips
|
openslide_exists=0
|
||||||
if [ $? -eq 0 ]; then
|
if [ $enable_openslide -eq 1 ]; then
|
||||||
vips_version_found=$(PKG_CONFIG_PATH=$pkg_config_path pkg-config --modversion vips)
|
check_if_library_exists "openslide" "$openslide_version_minimum"
|
||||||
pkg-config --atleast-version=$vips_version_minimum vips
|
openslide_exists=$?
|
||||||
if [ $? -eq 0 ]; then
|
fi
|
||||||
# Found suitable version of libvips
|
|
||||||
echo "Found libvips $vips_version_found"
|
check_if_library_exists "vips" "$vips_version_minimum"
|
||||||
exit 0
|
vips_exists=$?
|
||||||
|
if [ $vips_exists -eq 1 ] && [ $enable_openslide -eq 1 ]; then
|
||||||
|
if [ $openslide_exists -eq 1 ]; then
|
||||||
|
# Check if vips compiled with openslide support
|
||||||
|
vips_with_openslide=`vips list classes | grep -i opensli`
|
||||||
|
if [ -z $vips_with_openslide ]; then
|
||||||
|
echo "Vips compiled without openslide support."
|
||||||
|
else
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
fi
|
fi
|
||||||
echo "Found libvips $vips_version_found but require $vips_version_minimum"
|
elif [ $vips_exists -eq 1 ] && [ $enable_openslide -eq 0 ]; then
|
||||||
else
|
exit 0
|
||||||
echo "Could not find libvips using a PKG_CONFIG_PATH of '$pkg_config_path'"
|
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Verify root/sudo access
|
# Verify root/sudo access
|
||||||
@@ -65,101 +117,208 @@ if [ "$(id -u)" -ne "0" ]; then
|
|||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
# OS-specific installations of libopenslide follows
|
||||||
|
# Either openslide does not exist, or vips is installed without openslide support
|
||||||
|
if [ $enable_openslide -eq 1 ] && [ -z $vips_with_openslide ] && [ $openslide_exists -eq 0 ]; then
|
||||||
|
if [ -f /etc/debian_version ]; then
|
||||||
|
# Debian Linux
|
||||||
|
DISTRO=$(lsb_release -c -s)
|
||||||
|
echo "Detected Debian Linux '$DISTRO'"
|
||||||
|
case "$DISTRO" in
|
||||||
|
jessie|vivid)
|
||||||
|
# Debian 8, Ubuntu 15
|
||||||
|
echo "Installing libopenslide via apt-get"
|
||||||
|
apt-get install -y libopenslide-dev
|
||||||
|
;;
|
||||||
|
trusty|utopic|qiana|rebecca|rafaela)
|
||||||
|
# Ubuntu 14, Mint 17
|
||||||
|
echo "Installing libopenslide dependencies via apt-get"
|
||||||
|
apt-get install -y automake build-essential curl zlib1g-dev libopenjpeg-dev libpng12-dev libjpeg-dev libtiff5-dev libgdk-pixbuf2.0-dev libxml2-dev libsqlite3-dev libcairo2-dev libglib2.0-dev sqlite3 libsqlite3-dev
|
||||||
|
install_libopenslide_from_source
|
||||||
|
;;
|
||||||
|
precise|wheezy|maya)
|
||||||
|
# Debian 7, Ubuntu 12.04, Mint 13
|
||||||
|
echo "Installing libopenslide dependencies via apt-get"
|
||||||
|
apt-get install -y automake build-essential curl zlib1g-dev libopenjpeg-dev libpng12-dev libjpeg-dev libtiff5-dev libgdk-pixbuf2.0-dev libxml2-dev libsqlite3-dev libcairo2-dev libglib2.0-dev sqlite3 libsqlite3-dev
|
||||||
|
install_libopenslide_from_source
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
# Unsupported Debian-based OS
|
||||||
|
sorry "openslide" "Debian-based $DISTRO"
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
elif [ -f /etc/redhat-release ]; then
|
||||||
|
# Red Hat Linux
|
||||||
|
RELEASE=$(cat /etc/redhat-release)
|
||||||
|
echo "Detected Red Hat Linux '$RELEASE'"
|
||||||
|
case $RELEASE in
|
||||||
|
"Red Hat Enterprise Linux release 7."*|"CentOS Linux release 7."*|"Scientific Linux release 7."*)
|
||||||
|
# RHEL/CentOS 7
|
||||||
|
echo "Installing libopenslide dependencies via yum"
|
||||||
|
yum groupinstall -y "Development Tools"
|
||||||
|
yum install -y tar curl libpng-devel libjpeg-devel libxml2-devel zlib-devel openjpeg-devel libtiff-devel gdk-pixbuf2-devel sqlite-devel cairo-devel glib2-devel
|
||||||
|
install_libopenslide_from_source "--prefix=/usr"
|
||||||
|
;;
|
||||||
|
"Red Hat Enterprise Linux release 6."*|"CentOS release 6."*|"Scientific Linux release 6."*)
|
||||||
|
# RHEL/CentOS 6
|
||||||
|
echo "Installing libopenslide dependencies via yum"
|
||||||
|
yum groupinstall -y "Development Tools"
|
||||||
|
yum install -y tar curl libpng-devel libjpeg-devel libxml2-devel zlib-devel openjpeg-devel libtiff-devel gdk-pixbuf2-devel sqlite-devel cairo-devel glib2-devel
|
||||||
|
install_libopenslide_from_source "--prefix=/usr"
|
||||||
|
;;
|
||||||
|
"Fedora release 21 "*|"Fedora release 22 "*)
|
||||||
|
# Fedora 21, 22
|
||||||
|
echo "Installing libopenslide via yum"
|
||||||
|
yum install -y openslide-devel
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
# Unsupported RHEL-based OS
|
||||||
|
sorry "openslide" "$RELEASE"
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
elif [ -f /etc/os-release ]; then
|
||||||
|
RELEASE=$(cat /etc/os-release | grep VERSION)
|
||||||
|
echo "Detected OpenSuse Linux '$RELEASE'"
|
||||||
|
case $RELEASE in
|
||||||
|
*"13.2"*)
|
||||||
|
echo "Installing libopenslide via zypper"
|
||||||
|
zypper --gpg-auto-import-keys install -y libopenslide-devel
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
elif [ -f /etc/SuSE-brand ]; then
|
||||||
|
RELEASE=$(cat /etc/SuSE-brand | grep VERSION)
|
||||||
|
echo "Detected OpenSuse Linux '$RELEASE'"
|
||||||
|
case $RELEASE in
|
||||||
|
*"13.1")
|
||||||
|
echo "Installing libopenslide dependencies via zypper"
|
||||||
|
zypper --gpg-auto-import-keys install -y --type pattern devel_basis
|
||||||
|
zypper --gpg-auto-import-keys install -y tar curl libpng16-devel libjpeg-turbo libjpeg8-devel libxml2-devel zlib-devel openjpeg-devel libtiff-devel libgdk_pixbuf-2_0-0 sqlite3-devel cairo-devel glib2-devel
|
||||||
|
install_libopenslide_from_source
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
else
|
||||||
|
# Unsupported OS
|
||||||
|
sorry "openslide" "$(uname -a)"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
# OS-specific installations of libvips follows
|
# OS-specific installations of libvips follows
|
||||||
|
|
||||||
case $(uname -s) in
|
if [ -f /etc/debian_version ]; then
|
||||||
*[Dd]arwin*)
|
# Debian Linux
|
||||||
# Mac OS
|
DISTRO=$(lsb_release -c -s)
|
||||||
echo "Detected Mac OS"
|
echo "Detected Debian Linux '$DISTRO'"
|
||||||
if type "brew" > /dev/null; then
|
case "$DISTRO" in
|
||||||
echo "Installing libvips via homebrew"
|
jessie|vivid)
|
||||||
brew install homebrew/science/vips --with-webp --with-graphicsmagick
|
# Debian 8, Ubuntu 15
|
||||||
elif type "port" > /dev/null; then
|
if [ $enable_openslide -eq 1 ]; then
|
||||||
echo "Installing libvips via MacPorts"
|
echo "Recompiling vips with openslide support"
|
||||||
port install vips
|
install_libvips_from_source
|
||||||
else
|
else
|
||||||
sorry "Mac OS without homebrew or MacPorts"
|
echo "Installing libvips via apt-get"
|
||||||
fi
|
apt-get install -y libvips-dev libgsf-1-dev
|
||||||
|
fi
|
||||||
|
;;
|
||||||
|
trusty|utopic|qiana|rebecca|rafaela)
|
||||||
|
# Ubuntu 14, Mint 17
|
||||||
|
echo "Installing libvips dependencies via apt-get"
|
||||||
|
apt-get install -y automake build-essential gobject-introspection gtk-doc-tools libglib2.0-dev libjpeg-dev libpng12-dev libwebp-dev libtiff5-dev libexif-dev libgsf-1-dev liblcms2-dev libxml2-dev swig libmagickcore-dev curl
|
||||||
|
install_libvips_from_source
|
||||||
|
;;
|
||||||
|
precise|wheezy|maya)
|
||||||
|
# Debian 7, Ubuntu 12.04, Mint 13
|
||||||
|
echo "Installing libvips dependencies via apt-get"
|
||||||
|
add-apt-repository -y ppa:lyrasis/precise-backports
|
||||||
|
apt-get update
|
||||||
|
apt-get install -y automake build-essential gobject-introspection gtk-doc-tools libglib2.0-dev libjpeg-dev libpng12-dev libwebp-dev libtiff4-dev libexif-dev libgsf-1-dev liblcms2-dev libxml2-dev swig libmagickcore-dev curl
|
||||||
|
install_libvips_from_source
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
# Unsupported Debian-based OS
|
||||||
|
sorry "vips" "Debian-based $DISTRO"
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
elif [ -f /etc/redhat-release ]; then
|
||||||
|
# Red Hat Linux
|
||||||
|
RELEASE=$(cat /etc/redhat-release)
|
||||||
|
echo "Detected Red Hat Linux '$RELEASE'"
|
||||||
|
case $RELEASE in
|
||||||
|
"Red Hat Enterprise Linux release 7."*|"CentOS Linux release 7."*|"Scientific Linux release 7."*)
|
||||||
|
# RHEL/CentOS 7
|
||||||
|
echo "Installing libvips dependencies via yum"
|
||||||
|
yum groupinstall -y "Development Tools"
|
||||||
|
yum install -y gtk-doc libxml2-devel libjpeg-turbo-devel libpng-devel libtiff-devel libexif-devel libgsf-devel lcms-devel ImageMagick-devel gobject-introspection-devel libwebp-devel curl
|
||||||
|
install_libvips_from_source "--prefix=/usr"
|
||||||
|
;;
|
||||||
|
"Red Hat Enterprise Linux release 6."*|"CentOS release 6."*|"Scientific Linux release 6."*)
|
||||||
|
# RHEL/CentOS 6
|
||||||
|
echo "Installing libvips dependencies via yum"
|
||||||
|
yum groupinstall -y "Development Tools"
|
||||||
|
yum install -y gtk-doc libxml2-devel libjpeg-turbo-devel libpng-devel libtiff-devel libexif-devel libgsf-devel lcms-devel ImageMagick-devel curl
|
||||||
|
yum install -y http://li.nux.ro/download/nux/dextop/el6/x86_64/nux-dextop-release-0-2.el6.nux.noarch.rpm
|
||||||
|
yum install -y --enablerepo=nux-dextop gobject-introspection-devel
|
||||||
|
yum install -y http://rpms.famillecollet.com/enterprise/remi-release-6.rpm
|
||||||
|
yum install -y --enablerepo=remi libwebp-devel
|
||||||
|
install_libvips_from_source "--prefix=/usr"
|
||||||
|
;;
|
||||||
|
"Fedora release 21 "*|"Fedora release 22 "*)
|
||||||
|
# Fedora 21, 22
|
||||||
|
if [ $enable_openslide -eq 1 ]; then
|
||||||
|
echo "Installing libvips dependencies via yum"
|
||||||
|
yum groupinstall -y "Development Tools"
|
||||||
|
yum install -y gcc-c++ gtk-doc libxml2-devel libjpeg-turbo-devel libpng-devel libtiff-devel libexif-devel lcms-devel ImageMagick-devel gobject-introspection-devel libwebp-devel curl
|
||||||
|
echo "Compiling vips with openslide support"
|
||||||
|
install_libvips_from_source "--prefix=/usr"
|
||||||
|
else
|
||||||
|
echo "Installing libvips via yum"
|
||||||
|
yum install -y vips-devel
|
||||||
|
fi
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
# Unsupported RHEL-based OS
|
||||||
|
sorry "vips" "$RELEASE"
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
elif [ -f /etc/system-release ]; then
|
||||||
|
# Probably Amazon Linux
|
||||||
|
RELEASE=$(cat /etc/system-release)
|
||||||
|
case $RELEASE in
|
||||||
|
"Amazon Linux AMI release 2014.09"|"Amazon Linux AMI release 2015.03")
|
||||||
|
# Amazon Linux
|
||||||
|
echo "Detected '$RELEASE'"
|
||||||
|
echo "Installing libvips dependencies via yum"
|
||||||
|
yum groupinstall -y "Development Tools"
|
||||||
|
yum install -y gtk-doc libxml2-devel libjpeg-turbo-devel libpng-devel libtiff-devel libexif-devel libgsf-devel lcms-devel ImageMagick-devel gobject-introspection-devel libwebp-devel curl
|
||||||
|
install_libvips_from_source "--prefix=/usr"
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
# Unsupported Amazon Linux version
|
||||||
|
sorry "vips" "$RELEASE"
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
elif [ -f /etc/os-release ]; then
|
||||||
|
RELEASE=$(cat /etc/os-release | grep VERSION)
|
||||||
|
echo "Detected OpenSuse Linux '$RELEASE'"
|
||||||
|
case $RELEASE in
|
||||||
|
*"13.2"*)
|
||||||
|
echo "Installing libvips dependencies via zypper"
|
||||||
|
zypper --gpg-auto-import-keys install -y --type pattern devel_basis
|
||||||
|
zypper --gpg-auto-import-keys install -y tar curl gtk-doc libxml2-devel libjpeg-turbo libjpeg8-devel libpng16-devel libtiff-devel libexif-devel liblcms2-devel ImageMagick-devel gobject-introspection-devel libwebp-devel
|
||||||
|
install_libvips_from_source
|
||||||
;;
|
;;
|
||||||
*)
|
esac
|
||||||
if [ -f /etc/debian_version ]; then
|
elif [ -f /etc/SuSE-brand ]; then
|
||||||
# Debian Linux
|
RELEASE=$(cat /etc/SuSE-brand | grep VERSION)
|
||||||
DISTRO=$(lsb_release -c -s)
|
echo "Detected OpenSuse Linux '$RELEASE'"
|
||||||
echo "Detected Debian Linux '$DISTRO'"
|
case $RELEASE in
|
||||||
case "$DISTRO" in
|
*"13.1")
|
||||||
jessie|vivid)
|
echo "Installing libvips dependencies via zypper"
|
||||||
# Debian 8, Ubuntu 15
|
zypper --gpg-auto-import-keys install -y --type pattern devel_basis
|
||||||
echo "Installing libvips via apt-get"
|
zypper --gpg-auto-import-keys install -y tar curl gtk-doc libxml2-devel libjpeg-turbo libjpeg8-devel libpng16-devel libtiff-devel libexif-devel liblcms2-devel ImageMagick-devel gobject-introspection-devel libwebp-devel
|
||||||
apt-get install -y libvips-dev
|
install_libvips_from_source
|
||||||
;;
|
|
||||||
trusty|utopic|qiana|rebecca)
|
|
||||||
# Ubuntu 14, Mint 17
|
|
||||||
echo "Installing libvips dependencies via apt-get"
|
|
||||||
apt-get install -y automake build-essential gobject-introspection gtk-doc-tools libglib2.0-dev libjpeg-turbo8-dev libpng12-dev libwebp-dev libtiff5-dev libexif-dev liblcms2-dev libxml2-dev swig libmagickwand-dev curl
|
|
||||||
install_libvips_from_source
|
|
||||||
;;
|
|
||||||
precise|wheezy|maya)
|
|
||||||
# Debian 7, Ubuntu 12.04, Mint 13
|
|
||||||
echo "Installing libvips dependencies via apt-get"
|
|
||||||
add-apt-repository -y ppa:lyrasis/precise-backports
|
|
||||||
apt-get update
|
|
||||||
apt-get install -y automake build-essential gobject-introspection gtk-doc-tools libglib2.0-dev libjpeg-turbo8-dev libpng12-dev libwebp-dev libtiff4-dev libexif-dev liblcms2-dev libxml2-dev swig libmagickwand-dev curl
|
|
||||||
install_libvips_from_source
|
|
||||||
;;
|
|
||||||
*)
|
|
||||||
# Unsupported Debian-based OS
|
|
||||||
sorry "Debian-based $DISTRO"
|
|
||||||
;;
|
|
||||||
esac
|
|
||||||
elif [ -f /etc/redhat-release ]; then
|
|
||||||
# Red Hat Linux
|
|
||||||
RELEASE=$(cat /etc/redhat-release)
|
|
||||||
echo "Detected Red Hat Linux '$RELEASE'"
|
|
||||||
case $RELEASE in
|
|
||||||
"Red Hat Enterprise Linux release 7."*|"CentOS Linux release 7."*|"Scientific Linux release 7."*)
|
|
||||||
# RHEL/CentOS 7
|
|
||||||
echo "Installing libvips dependencies via yum"
|
|
||||||
yum groupinstall -y "Development Tools"
|
|
||||||
yum install -y gtk-doc libxml2-devel libjpeg-turbo-devel libpng-devel libtiff-devel libexif-devel lcms-devel ImageMagick-devel gobject-introspection-devel libwebp-devel curl
|
|
||||||
install_libvips_from_source "--prefix=/usr"
|
|
||||||
;;
|
|
||||||
"Red Hat Enterprise Linux release 6."*|"CentOS release 6."*|"Scientific Linux release 6."*)
|
|
||||||
# RHEL/CentOS 6
|
|
||||||
echo "Installing libvips dependencies via yum"
|
|
||||||
yum groupinstall -y "Development Tools"
|
|
||||||
yum install -y gtk-doc libxml2-devel libjpeg-turbo-devel libpng-devel libtiff-devel libexif-devel lcms-devel ImageMagick-devel curl
|
|
||||||
yum install -y http://li.nux.ro/download/nux/dextop/el6/x86_64/nux-dextop-release-0-2.el6.nux.noarch.rpm
|
|
||||||
yum install -y --enablerepo=nux-dextop gobject-introspection-devel
|
|
||||||
yum install -y http://rpms.famillecollet.com/enterprise/remi-release-6.rpm
|
|
||||||
yum install -y --enablerepo=remi libwebp-devel
|
|
||||||
install_libvips_from_source "--prefix=/usr"
|
|
||||||
;;
|
|
||||||
"Fedora release 21 "*|"Fedora release 22 "*)
|
|
||||||
# Fedora 21, 22
|
|
||||||
echo "Installing libvips via yum"
|
|
||||||
yum install vips-devel
|
|
||||||
;;
|
|
||||||
*)
|
|
||||||
# Unsupported RHEL-based OS
|
|
||||||
sorry "$RELEASE"
|
|
||||||
;;
|
|
||||||
esac
|
|
||||||
elif [ -f /etc/system-release ]; then
|
|
||||||
# Probably Amazon Linux
|
|
||||||
RELEASE=$(cat /etc/system-release)
|
|
||||||
case $RELEASE in
|
|
||||||
"Amazon Linux AMI release 2014.09")
|
|
||||||
# Amazon Linux
|
|
||||||
echo "Detected '$RELEASE'"
|
|
||||||
echo "Installing libvips dependencies via yum"
|
|
||||||
yum groupinstall -y "Development Tools"
|
|
||||||
yum install -y gtk-doc libxml2-devel libjpeg-turbo-devel libpng-devel libtiff-devel libexif-devel lcms-devel ImageMagick-devel gobject-introspection-devel libwebp-devel curl
|
|
||||||
install_libvips_from_source "--prefix=/usr"
|
|
||||||
;;
|
|
||||||
esac
|
|
||||||
else
|
|
||||||
# Unsupported OS
|
|
||||||
sorry "$(uname -a)"
|
|
||||||
fi
|
|
||||||
;;
|
;;
|
||||||
esac
|
esac
|
||||||
|
else
|
||||||
|
# Unsupported OS
|
||||||
|
sorry "vips" "$(uname -a)"
|
||||||
|
fi
|
||||||
|
|||||||
135
src/common.cc
@@ -1,9 +1,32 @@
|
|||||||
|
#include <cstdlib>
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <string.h>
|
#include <string.h>
|
||||||
#include <vips/vips.h>
|
#include <vips/vips.h>
|
||||||
|
|
||||||
#include "common.h"
|
#include "common.h"
|
||||||
|
|
||||||
|
// Verify platform and compiler compatibility
|
||||||
|
|
||||||
|
#if (VIPS_MAJOR_VERSION < 7 || (VIPS_MAJOR_VERSION == 7 && VIPS_MINOR_VERSION < 40))
|
||||||
|
#error libvips version 7.40.0+ required - see http://sharp.dimens.io/page/install
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef _WIN64
|
||||||
|
#error Windows 64-bit is currently unsupported - see http://sharp.dimens.io/page/install#windows
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if ((!defined(__clang__)) && defined(__GNUC__) && (__GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 6)))
|
||||||
|
#error GCC version 4.6+ is required for C++11 features - see http://sharp.dimens.io/page/install#prerequisites
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if (defined(__clang__) && defined(__has_feature))
|
||||||
|
#if (!__has_feature(cxx_range_for))
|
||||||
|
#error clang version 3.0+ is required for C++11 features - see http://sharp.dimens.io/page/install#prerequisites
|
||||||
|
#endif
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#define EXIF_IFD0_ORIENTATION "exif-ifd0-Orientation"
|
||||||
|
|
||||||
namespace sharp {
|
namespace sharp {
|
||||||
|
|
||||||
// How many tasks are in the queue?
|
// How many tasks are in the queue?
|
||||||
@@ -28,19 +51,8 @@ namespace sharp {
|
|||||||
bool IsTiff(std::string const &str) {
|
bool IsTiff(std::string const &str) {
|
||||||
return EndsWith(str, ".tif") || EndsWith(str, ".tiff") || EndsWith(str, ".TIF") || EndsWith(str, ".TIFF");
|
return EndsWith(str, ".tif") || EndsWith(str, ".tiff") || EndsWith(str, ".TIF") || EndsWith(str, ".TIFF");
|
||||||
}
|
}
|
||||||
|
bool IsDz(std::string const &str) {
|
||||||
// Buffer content checkers
|
return EndsWith(str, ".dzi") || EndsWith(str, ".DZI");
|
||||||
unsigned char const MARKER_JPEG[] = {0xff, 0xd8};
|
|
||||||
unsigned char const MARKER_PNG[] = {0x89, 0x50};
|
|
||||||
unsigned char const MARKER_WEBP[] = {0x52, 0x49};
|
|
||||||
|
|
||||||
static bool buffer_is_tiff(char *buffer, size_t len) {
|
|
||||||
return (
|
|
||||||
len >= 4 && (
|
|
||||||
(buffer[0] == 'M' && buffer[1] == 'M' && buffer[2] == '\0' && (buffer[3] == '*' || buffer[3] == '+')) ||
|
|
||||||
(buffer[0] == 'I' && buffer[1] == 'I' && (buffer[2] == '*' || buffer[2] == '+') && buffer[3] == '\0')
|
|
||||||
)
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -48,15 +60,19 @@ namespace sharp {
|
|||||||
*/
|
*/
|
||||||
ImageType DetermineImageType(void *buffer, size_t const length) {
|
ImageType DetermineImageType(void *buffer, size_t const length) {
|
||||||
ImageType imageType = ImageType::UNKNOWN;
|
ImageType imageType = ImageType::UNKNOWN;
|
||||||
if (length >= 4) {
|
char const *load = vips_foreign_find_load_buffer(buffer, length);
|
||||||
if (memcmp(MARKER_JPEG, buffer, 2) == 0) {
|
if (load != NULL) {
|
||||||
|
std::string loader = load;
|
||||||
|
if (EndsWith(loader, "JpegBuffer")) {
|
||||||
imageType = ImageType::JPEG;
|
imageType = ImageType::JPEG;
|
||||||
} else if (memcmp(MARKER_PNG, buffer, 2) == 0) {
|
} else if (EndsWith(loader, "PngBuffer")) {
|
||||||
imageType = ImageType::PNG;
|
imageType = ImageType::PNG;
|
||||||
} else if (memcmp(MARKER_WEBP, buffer, 2) == 0) {
|
} else if (EndsWith(loader, "WebpBuffer")) {
|
||||||
imageType = ImageType::WEBP;
|
imageType = ImageType::WEBP;
|
||||||
} else if (buffer_is_tiff(static_cast<char*>(buffer), length)) {
|
} else if (EndsWith(loader, "TiffBuffer")) {
|
||||||
imageType = ImageType::TIFF;
|
imageType = ImageType::TIFF;
|
||||||
|
} else if (EndsWith(loader, "MagickBuffer")) {
|
||||||
|
imageType = ImageType::MAGICK;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return imageType;
|
return imageType;
|
||||||
@@ -65,35 +81,31 @@ namespace sharp {
|
|||||||
/*
|
/*
|
||||||
Initialise and return a VipsImage from a buffer. Supports JPEG, PNG, WebP and TIFF.
|
Initialise and return a VipsImage from a buffer. Supports JPEG, PNG, WebP and TIFF.
|
||||||
*/
|
*/
|
||||||
VipsImage* InitImage(ImageType imageType, void *buffer, size_t const length, VipsAccess const access) {
|
VipsImage* InitImage(void *buffer, size_t const length, VipsAccess const access) {
|
||||||
VipsImage *image = NULL;
|
return vips_image_new_from_buffer(buffer, length, NULL, "access", access, NULL);
|
||||||
if (imageType == ImageType::JPEG) {
|
|
||||||
vips_jpegload_buffer(buffer, length, &image, "access", access, NULL);
|
|
||||||
} else if (imageType == ImageType::PNG) {
|
|
||||||
vips_pngload_buffer(buffer, length, &image, "access", access, NULL);
|
|
||||||
} else if (imageType == ImageType::WEBP) {
|
|
||||||
vips_webpload_buffer(buffer, length, &image, "access", access, NULL);
|
|
||||||
} else if (imageType == ImageType::TIFF) {
|
|
||||||
vips_tiffload_buffer(buffer, length, &image, "access", access, NULL);
|
|
||||||
}
|
|
||||||
return image;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Inpect the first 2-4 bytes of a file to determine image format
|
Determine image format, reads the first few bytes of the file
|
||||||
*/
|
*/
|
||||||
ImageType DetermineImageType(char const *file) {
|
ImageType DetermineImageType(char const *file) {
|
||||||
ImageType imageType = ImageType::UNKNOWN;
|
ImageType imageType = ImageType::UNKNOWN;
|
||||||
if (vips_foreign_is_a("jpegload", file)) {
|
char const *load = vips_foreign_find_load(file);
|
||||||
imageType = ImageType::JPEG;
|
if (load != NULL) {
|
||||||
} else if (vips_foreign_is_a("pngload", file)) {
|
std::string loader = load;
|
||||||
imageType = ImageType::PNG;
|
if (EndsWith(loader, "JpegFile")) {
|
||||||
} else if (vips_foreign_is_a("webpload", file)) {
|
imageType = ImageType::JPEG;
|
||||||
imageType = ImageType::WEBP;
|
} else if (EndsWith(loader, "Png")) {
|
||||||
} else if (vips_foreign_is_a("tiffload", file)) {
|
imageType = ImageType::PNG;
|
||||||
imageType = ImageType::TIFF;
|
} else if (EndsWith(loader, "WebpFile")) {
|
||||||
} else if(vips_foreign_is_a("magickload", file)) {
|
imageType = ImageType::WEBP;
|
||||||
imageType = ImageType::MAGICK;
|
} else if (EndsWith(loader, "Openslide")) {
|
||||||
|
imageType = ImageType::OPENSLIDE;
|
||||||
|
} else if (EndsWith(loader, "TiffFile")) {
|
||||||
|
imageType = ImageType::TIFF;
|
||||||
|
} else if (EndsWith(loader, "Magick") || EndsWith(loader, "MagickFile")) {
|
||||||
|
imageType = ImageType::MAGICK;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return imageType;
|
return imageType;
|
||||||
}
|
}
|
||||||
@@ -101,20 +113,8 @@ namespace sharp {
|
|||||||
/*
|
/*
|
||||||
Initialise and return a VipsImage from a file.
|
Initialise and return a VipsImage from a file.
|
||||||
*/
|
*/
|
||||||
VipsImage* InitImage(ImageType imageType, char const *file, VipsAccess const access) {
|
VipsImage* InitImage(char const *file, VipsAccess const access) {
|
||||||
VipsImage *image = NULL;
|
return vips_image_new_from_file(file, "access", access, NULL);
|
||||||
if (imageType == ImageType::JPEG) {
|
|
||||||
vips_jpegload(file, &image, "access", access, NULL);
|
|
||||||
} else if (imageType == ImageType::PNG) {
|
|
||||||
vips_pngload(file, &image, "access", access, NULL);
|
|
||||||
} else if (imageType == ImageType::WEBP) {
|
|
||||||
vips_webpload(file, &image, "access", access, NULL);
|
|
||||||
} else if (imageType == ImageType::TIFF) {
|
|
||||||
vips_tiffload(file, &image, "access", access, NULL);
|
|
||||||
} else if (imageType == ImageType::MAGICK) {
|
|
||||||
vips_magickload(file, &image, "access", access, NULL);
|
|
||||||
}
|
|
||||||
return image;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -143,23 +143,42 @@ namespace sharp {
|
|||||||
int orientation = 0;
|
int orientation = 0;
|
||||||
const char *exif;
|
const char *exif;
|
||||||
if (
|
if (
|
||||||
vips_image_get_typeof(image, "exif-ifd0-Orientation") != 0 &&
|
vips_image_get_typeof(image, EXIF_IFD0_ORIENTATION) != 0 &&
|
||||||
!vips_image_get_string(image, "exif-ifd0-Orientation", &exif)
|
!vips_image_get_string(image, EXIF_IFD0_ORIENTATION, &exif)
|
||||||
) {
|
) {
|
||||||
orientation = atoi(&exif[0]);
|
orientation = atoi(&exif[0]);
|
||||||
}
|
}
|
||||||
return orientation;
|
return orientation;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
Set EXIF Orientation of image.
|
||||||
|
*/
|
||||||
|
void SetExifOrientation(VipsImage *image, int const orientation) {
|
||||||
|
char exif[3];
|
||||||
|
g_snprintf(exif, sizeof(exif), "%d", orientation);
|
||||||
|
vips_image_set_string(image, EXIF_IFD0_ORIENTATION, exif);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
Remove EXIF Orientation from image.
|
||||||
|
*/
|
||||||
|
void RemoveExifOrientation(VipsImage *image) {
|
||||||
|
vips_image_remove(image, EXIF_IFD0_ORIENTATION);
|
||||||
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Returns the window size for the named interpolator. For example,
|
Returns the window size for the named interpolator. For example,
|
||||||
a window size of 3 means a 3x3 pixel grid is used for the calculation.
|
a window size of 3 means a 3x3 pixel grid is used for the calculation.
|
||||||
*/
|
*/
|
||||||
int InterpolatorWindowSize(char const *name) {
|
int InterpolatorWindowSize(char const *name) {
|
||||||
VipsInterpolate *interpolator = vips_interpolate_new(name);
|
VipsInterpolate *interpolator = vips_interpolate_new(name);
|
||||||
|
if (interpolator == NULL) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
int window_size = vips_interpolate_get_window_size(interpolator);
|
int window_size = vips_interpolate_get_window_size(interpolator);
|
||||||
g_object_unref(interpolator);
|
g_object_unref(interpolator);
|
||||||
return window_size;
|
return window_size;
|
||||||
}
|
}
|
||||||
|
|
||||||
} // namespace
|
} // namespace sharp
|
||||||
|
|||||||
28
src/common.h
@@ -1,5 +1,7 @@
|
|||||||
#ifndef SHARP_COMMON_H
|
#ifndef SRC_COMMON_H_
|
||||||
#define SHARP_COMMON_H
|
#define SRC_COMMON_H_
|
||||||
|
|
||||||
|
#include <string>
|
||||||
|
|
||||||
namespace sharp {
|
namespace sharp {
|
||||||
|
|
||||||
@@ -9,7 +11,8 @@ namespace sharp {
|
|||||||
PNG,
|
PNG,
|
||||||
WEBP,
|
WEBP,
|
||||||
TIFF,
|
TIFF,
|
||||||
MAGICK
|
MAGICK,
|
||||||
|
OPENSLIDE
|
||||||
};
|
};
|
||||||
|
|
||||||
// How many tasks are in the queue?
|
// How many tasks are in the queue?
|
||||||
@@ -23,6 +26,7 @@ namespace sharp {
|
|||||||
bool IsPng(std::string const &str);
|
bool IsPng(std::string const &str);
|
||||||
bool IsWebp(std::string const &str);
|
bool IsWebp(std::string const &str);
|
||||||
bool IsTiff(std::string const &str);
|
bool IsTiff(std::string const &str);
|
||||||
|
bool IsDz(std::string const &str);
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Determine image format of a buffer.
|
Determine image format of a buffer.
|
||||||
@@ -37,12 +41,12 @@ namespace sharp {
|
|||||||
/*
|
/*
|
||||||
Initialise and return a VipsImage from a buffer. Supports JPEG, PNG, WebP and TIFF.
|
Initialise and return a VipsImage from a buffer. Supports JPEG, PNG, WebP and TIFF.
|
||||||
*/
|
*/
|
||||||
VipsImage* InitImage(ImageType imageType, void *buffer, size_t const length, VipsAccess const access);
|
VipsImage* InitImage(void *buffer, size_t const length, VipsAccess const access);
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Initialise and return a VipsImage from a file.
|
Initialise and return a VipsImage from a file.
|
||||||
*/
|
*/
|
||||||
VipsImage* InitImage(ImageType imageType, char const *file, VipsAccess const access);
|
VipsImage* InitImage(char const *file, VipsAccess const access);
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Does this image have an embedded profile?
|
Does this image have an embedded profile?
|
||||||
@@ -60,12 +64,22 @@ namespace sharp {
|
|||||||
*/
|
*/
|
||||||
int ExifOrientation(VipsImage const *image);
|
int ExifOrientation(VipsImage const *image);
|
||||||
|
|
||||||
|
/*
|
||||||
|
Set EXIF Orientation of image.
|
||||||
|
*/
|
||||||
|
void SetExifOrientation(VipsImage *image, int const orientation);
|
||||||
|
|
||||||
|
/*
|
||||||
|
Remove EXIF Orientation from image.
|
||||||
|
*/
|
||||||
|
void RemoveExifOrientation(VipsImage *image);
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Returns the window size for the named interpolator. For example,
|
Returns the window size for the named interpolator. For example,
|
||||||
a window size of 3 means a 3x3 pixel grid is used for the calculation.
|
a window size of 3 means a 3x3 pixel grid is used for the calculation.
|
||||||
*/
|
*/
|
||||||
int InterpolatorWindowSize(char const *name);
|
int InterpolatorWindowSize(char const *name);
|
||||||
|
|
||||||
} // namespace
|
} // namespace sharp
|
||||||
|
|
||||||
#endif
|
#endif // SRC_COMMON_H_
|
||||||
|
|||||||
@@ -6,13 +6,28 @@
|
|||||||
#include "common.h"
|
#include "common.h"
|
||||||
#include "metadata.h"
|
#include "metadata.h"
|
||||||
|
|
||||||
using namespace v8;
|
using v8::Handle;
|
||||||
using namespace sharp;
|
using v8::Local;
|
||||||
|
using v8::Value;
|
||||||
|
using v8::Object;
|
||||||
|
using v8::Number;
|
||||||
|
using v8::String;
|
||||||
|
using v8::Boolean;
|
||||||
|
using v8::Function;
|
||||||
|
using v8::Exception;
|
||||||
|
|
||||||
|
using sharp::ImageType;
|
||||||
|
using sharp::DetermineImageType;
|
||||||
|
using sharp::InitImage;
|
||||||
|
using sharp::HasProfile;
|
||||||
|
using sharp::HasAlpha;
|
||||||
|
using sharp::ExifOrientation;
|
||||||
|
using sharp::counterQueue;
|
||||||
|
|
||||||
struct MetadataBaton {
|
struct MetadataBaton {
|
||||||
// Input
|
// Input
|
||||||
std::string fileIn;
|
std::string fileIn;
|
||||||
void* bufferIn;
|
char *bufferIn;
|
||||||
size_t bufferInLength;
|
size_t bufferInLength;
|
||||||
// Output
|
// Output
|
||||||
std::string format;
|
std::string format;
|
||||||
@@ -23,13 +38,29 @@ struct MetadataBaton {
|
|||||||
bool hasProfile;
|
bool hasProfile;
|
||||||
bool hasAlpha;
|
bool hasAlpha;
|
||||||
int orientation;
|
int orientation;
|
||||||
|
char *exif;
|
||||||
|
size_t exifLength;
|
||||||
|
char *icc;
|
||||||
|
size_t iccLength;
|
||||||
std::string err;
|
std::string err;
|
||||||
|
|
||||||
MetadataBaton():
|
MetadataBaton():
|
||||||
bufferInLength(0),
|
bufferInLength(0),
|
||||||
orientation(0) {}
|
orientation(0),
|
||||||
|
exifLength(0),
|
||||||
|
iccLength(0) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/*
|
||||||
|
Delete input char[] buffer and notify V8 of memory deallocation
|
||||||
|
Used as the callback function for the "postclose" signal
|
||||||
|
*/
|
||||||
|
static void DeleteBuffer(VipsObject *object, char *buffer) {
|
||||||
|
if (buffer != NULL) {
|
||||||
|
delete[] buffer;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
class MetadataWorker : public NanAsyncWorker {
|
class MetadataWorker : public NanAsyncWorker {
|
||||||
|
|
||||||
public:
|
public:
|
||||||
@@ -42,21 +73,34 @@ class MetadataWorker : public NanAsyncWorker {
|
|||||||
|
|
||||||
ImageType imageType = ImageType::UNKNOWN;
|
ImageType imageType = ImageType::UNKNOWN;
|
||||||
VipsImage *image = NULL;
|
VipsImage *image = NULL;
|
||||||
if (baton->bufferInLength > 1) {
|
if (baton->bufferInLength > 0) {
|
||||||
// From buffer
|
// From buffer
|
||||||
imageType = DetermineImageType(baton->bufferIn, baton->bufferInLength);
|
imageType = DetermineImageType(baton->bufferIn, baton->bufferInLength);
|
||||||
if (imageType != ImageType::UNKNOWN) {
|
if (imageType != ImageType::UNKNOWN) {
|
||||||
image = InitImage(imageType, baton->bufferIn, baton->bufferInLength, VIPS_ACCESS_RANDOM);
|
image = InitImage(baton->bufferIn, baton->bufferInLength, VIPS_ACCESS_RANDOM);
|
||||||
|
if (image != NULL) {
|
||||||
|
// Listen for "postclose" signal to delete input buffer
|
||||||
|
g_signal_connect(image, "postclose", G_CALLBACK(DeleteBuffer), baton->bufferIn);
|
||||||
|
} else {
|
||||||
|
(baton->err).append("Input buffer has corrupt header");
|
||||||
|
imageType = ImageType::UNKNOWN;
|
||||||
|
DeleteBuffer(NULL, baton->bufferIn);
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
(baton->err).append("Input buffer contains unsupported image format");
|
(baton->err).append("Input buffer contains unsupported image format");
|
||||||
|
DeleteBuffer(NULL, baton->bufferIn);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// From file
|
// From file
|
||||||
imageType = DetermineImageType(baton->fileIn.c_str());
|
imageType = DetermineImageType(baton->fileIn.c_str());
|
||||||
if (imageType != ImageType::UNKNOWN) {
|
if (imageType != ImageType::UNKNOWN) {
|
||||||
image = InitImage(imageType, baton->fileIn.c_str(), VIPS_ACCESS_RANDOM);
|
image = InitImage(baton->fileIn.c_str(), VIPS_ACCESS_RANDOM);
|
||||||
|
if (image == NULL) {
|
||||||
|
(baton->err).append("Input file has corrupt header");
|
||||||
|
imageType = ImageType::UNKNOWN;
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
(baton->err).append("File is of an unsupported image format");
|
(baton->err).append("Input file is of an unsupported image format");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (image != NULL && imageType != ImageType::UNKNOWN) {
|
if (image != NULL && imageType != ImageType::UNKNOWN) {
|
||||||
@@ -67,6 +111,7 @@ class MetadataWorker : public NanAsyncWorker {
|
|||||||
case ImageType::WEBP: baton->format = "webp"; break;
|
case ImageType::WEBP: baton->format = "webp"; break;
|
||||||
case ImageType::TIFF: baton->format = "tiff"; break;
|
case ImageType::TIFF: baton->format = "tiff"; break;
|
||||||
case ImageType::MAGICK: baton->format = "magick"; break;
|
case ImageType::MAGICK: baton->format = "magick"; break;
|
||||||
|
case ImageType::OPENSLIDE: baton->format = "openslide"; break;
|
||||||
case ImageType::UNKNOWN: break;
|
case ImageType::UNKNOWN: break;
|
||||||
}
|
}
|
||||||
// VipsImage attributes
|
// VipsImage attributes
|
||||||
@@ -78,6 +123,26 @@ class MetadataWorker : public NanAsyncWorker {
|
|||||||
// Derived attributes
|
// Derived attributes
|
||||||
baton->hasAlpha = HasAlpha(image);
|
baton->hasAlpha = HasAlpha(image);
|
||||||
baton->orientation = ExifOrientation(image);
|
baton->orientation = ExifOrientation(image);
|
||||||
|
// EXIF
|
||||||
|
if (vips_image_get_typeof(image, VIPS_META_EXIF_NAME) == VIPS_TYPE_BLOB) {
|
||||||
|
void* exif;
|
||||||
|
size_t exifLength;
|
||||||
|
if (!vips_image_get_blob(image, VIPS_META_EXIF_NAME, &exif, &exifLength)) {
|
||||||
|
baton->exifLength = exifLength;
|
||||||
|
baton->exif = new char[exifLength];
|
||||||
|
memcpy(baton->exif, exif, exifLength);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// ICC profile
|
||||||
|
if (vips_image_get_typeof(image, VIPS_META_ICC_NAME) == VIPS_TYPE_BLOB) {
|
||||||
|
void* icc;
|
||||||
|
size_t iccLength;
|
||||||
|
if (!vips_image_get_blob(image, VIPS_META_ICC_NAME, &icc, &iccLength)) {
|
||||||
|
baton->iccLength = iccLength;
|
||||||
|
baton->icc = new char[iccLength];
|
||||||
|
memcpy(baton->icc, icc, iccLength);
|
||||||
|
}
|
||||||
|
}
|
||||||
// Drop image reference
|
// Drop image reference
|
||||||
g_object_unref(image);
|
g_object_unref(image);
|
||||||
}
|
}
|
||||||
@@ -106,6 +171,12 @@ class MetadataWorker : public NanAsyncWorker {
|
|||||||
if (baton->orientation > 0) {
|
if (baton->orientation > 0) {
|
||||||
info->Set(NanNew<String>("orientation"), NanNew<Number>(baton->orientation));
|
info->Set(NanNew<String>("orientation"), NanNew<Number>(baton->orientation));
|
||||||
}
|
}
|
||||||
|
if (baton->exifLength > 0) {
|
||||||
|
info->Set(NanNew<String>("exif"), NanBufferUse(baton->exif, baton->exifLength));
|
||||||
|
}
|
||||||
|
if (baton->iccLength > 0) {
|
||||||
|
info->Set(NanNew<String>("icc"), NanBufferUse(baton->icc, baton->iccLength));
|
||||||
|
}
|
||||||
argv[1] = info;
|
argv[1] = info;
|
||||||
}
|
}
|
||||||
delete baton;
|
delete baton;
|
||||||
@@ -133,8 +204,10 @@ NAN_METHOD(metadata) {
|
|||||||
// Input Buffer object
|
// Input Buffer object
|
||||||
if (options->Get(NanNew<String>("bufferIn"))->IsObject()) {
|
if (options->Get(NanNew<String>("bufferIn"))->IsObject()) {
|
||||||
Local<Object> buffer = options->Get(NanNew<String>("bufferIn"))->ToObject();
|
Local<Object> buffer = options->Get(NanNew<String>("bufferIn"))->ToObject();
|
||||||
|
// Take a copy of the input Buffer to avoid problems with V8 heap compaction
|
||||||
baton->bufferInLength = node::Buffer::Length(buffer);
|
baton->bufferInLength = node::Buffer::Length(buffer);
|
||||||
baton->bufferIn = node::Buffer::Data(buffer);
|
baton->bufferIn = new char[baton->bufferInLength];
|
||||||
|
memcpy(baton->bufferIn, node::Buffer::Data(buffer), baton->bufferInLength);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Join queue for worker thread
|
// Join queue for worker thread
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
#ifndef SHARP_METADATA_H
|
#ifndef SRC_METADATA_H_
|
||||||
#define SHARP_METADATA_H
|
#define SRC_METADATA_H_
|
||||||
|
|
||||||
#include "nan.h"
|
#include "nan.h"
|
||||||
|
|
||||||
NAN_METHOD(metadata);
|
NAN_METHOD(metadata);
|
||||||
|
|
||||||
#endif
|
#endif // SRC_METADATA_H_
|
||||||
|
|||||||
333
src/operations.cc
Executable file
@@ -0,0 +1,333 @@
|
|||||||
|
#include <vips/vips.h>
|
||||||
|
|
||||||
|
#include "common.h"
|
||||||
|
#include "operations.h"
|
||||||
|
|
||||||
|
namespace sharp {
|
||||||
|
|
||||||
|
/*
|
||||||
|
Alpha composite src over dst
|
||||||
|
Assumes alpha channels are already premultiplied and will be unpremultiplied after
|
||||||
|
*/
|
||||||
|
int Composite(VipsObject *context, VipsImage *src, VipsImage *dst, VipsImage **out) {
|
||||||
|
using sharp::HasAlpha;
|
||||||
|
|
||||||
|
// Split src into non-alpha and alpha
|
||||||
|
VipsImage *srcWithoutAlpha;
|
||||||
|
if (vips_extract_band(src, &srcWithoutAlpha, 0, "n", src->Bands - 1, NULL))
|
||||||
|
return -1;
|
||||||
|
vips_object_local(context, srcWithoutAlpha);
|
||||||
|
VipsImage *srcAlpha;
|
||||||
|
if (vips_extract_band(src, &srcAlpha, src->Bands - 1, "n", 1, NULL))
|
||||||
|
return -1;
|
||||||
|
vips_object_local(context, srcAlpha);
|
||||||
|
|
||||||
|
// Split dst into non-alpha and alpha channels
|
||||||
|
VipsImage *dstWithoutAlpha;
|
||||||
|
VipsImage *dstAlpha;
|
||||||
|
if (HasAlpha(dst)) {
|
||||||
|
// Non-alpha: extract all-but-last channel
|
||||||
|
if (vips_extract_band(dst, &dstWithoutAlpha, 0, "n", dst->Bands - 1, NULL)) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
vips_object_local(context, dstWithoutAlpha);
|
||||||
|
// Alpha: Extract last channel
|
||||||
|
if (vips_extract_band(dst, &dstAlpha, dst->Bands - 1, "n", 1, NULL)) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
vips_object_local(context, dstAlpha);
|
||||||
|
} else {
|
||||||
|
// Non-alpha: Copy reference
|
||||||
|
dstWithoutAlpha = dst;
|
||||||
|
// Alpha: Use blank, opaque (0xFF) image
|
||||||
|
VipsImage *black;
|
||||||
|
if (vips_black(&black, dst->Xsize, dst->Ysize, NULL)) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
vips_object_local(context, black);
|
||||||
|
if (vips_invert(black, &dstAlpha, NULL)) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
vips_object_local(context, dstAlpha);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Compute normalized input alpha channels:
|
||||||
|
VipsImage *srcAlphaNormalized;
|
||||||
|
if (vips_linear1(srcAlpha, &srcAlphaNormalized, 1.0 / 255.0, 0.0, NULL))
|
||||||
|
return -1;
|
||||||
|
vips_object_local(context, srcAlphaNormalized);
|
||||||
|
|
||||||
|
VipsImage *dstAlphaNormalized;
|
||||||
|
if (vips_linear1(dstAlpha, &dstAlphaNormalized, 1.0 / 255.0, 0.0, NULL))
|
||||||
|
return -1;
|
||||||
|
vips_object_local(context, dstAlphaNormalized);
|
||||||
|
|
||||||
|
//
|
||||||
|
// Compute normalized output alpha channel:
|
||||||
|
//
|
||||||
|
// References:
|
||||||
|
// - http://en.wikipedia.org/wiki/Alpha_compositing#Alpha_blending
|
||||||
|
// - https://github.com/jcupitt/ruby-vips/issues/28#issuecomment-9014826
|
||||||
|
//
|
||||||
|
// out_a = src_a + dst_a * (1 - src_a)
|
||||||
|
// ^^^^^^^^^^^
|
||||||
|
// t0
|
||||||
|
// ^^^^^^^^^^^^^^^^^^^
|
||||||
|
// t1
|
||||||
|
VipsImage *t0;
|
||||||
|
if (vips_linear1(srcAlphaNormalized, &t0, -1.0, 1.0, NULL))
|
||||||
|
return -1;
|
||||||
|
vips_object_local(context, t0);
|
||||||
|
|
||||||
|
VipsImage *t1;
|
||||||
|
if (vips_multiply(dstAlphaNormalized, t0, &t1, NULL))
|
||||||
|
return -1;
|
||||||
|
vips_object_local(context, t1);
|
||||||
|
|
||||||
|
VipsImage *outAlphaNormalized;
|
||||||
|
if (vips_add(srcAlphaNormalized, t1, &outAlphaNormalized, NULL))
|
||||||
|
return -1;
|
||||||
|
vips_object_local(context, outAlphaNormalized);
|
||||||
|
|
||||||
|
//
|
||||||
|
// Compute output RGB channels:
|
||||||
|
//
|
||||||
|
// Wikipedia:
|
||||||
|
// out_rgb = (src_rgb * src_a + dst_rgb * dst_a * (1 - src_a)) / out_a
|
||||||
|
// ^^^^^^^^^^^
|
||||||
|
// t0
|
||||||
|
//
|
||||||
|
// Omit division by `out_a` since `Compose` is supposed to output a
|
||||||
|
// premultiplied RGBA image as reversal of premultiplication is handled
|
||||||
|
// externally.
|
||||||
|
//
|
||||||
|
VipsImage *t2;
|
||||||
|
if (vips_multiply(dstWithoutAlpha, t0, &t2, NULL))
|
||||||
|
return -1;
|
||||||
|
vips_object_local(context, t2);
|
||||||
|
|
||||||
|
VipsImage *outRGBPremultiplied;
|
||||||
|
if (vips_add(srcWithoutAlpha, t2, &outRGBPremultiplied, NULL))
|
||||||
|
return -1;
|
||||||
|
vips_object_local(context, outRGBPremultiplied);
|
||||||
|
|
||||||
|
// Denormalize output alpha channel:
|
||||||
|
VipsImage *outAlpha;
|
||||||
|
if (vips_linear1(outAlphaNormalized, &outAlpha, 255.0, 0.0, NULL))
|
||||||
|
return -1;
|
||||||
|
vips_object_local(context, outAlpha);
|
||||||
|
|
||||||
|
// Combine RGB and alpha channel into output image:
|
||||||
|
return vips_bandjoin2(outRGBPremultiplied, outAlpha, out, NULL);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Premultiply alpha channel of `image`.
|
||||||
|
*/
|
||||||
|
int Premultiply(VipsObject *context, VipsImage *image, VipsImage **out) {
|
||||||
|
#if (VIPS_MAJOR_VERSION >= 9 || (VIPS_MAJOR_VERSION >= 8 && VIPS_MINOR_VERSION >= 1))
|
||||||
|
return vips_premultiply(image, out, NULL);
|
||||||
|
#else
|
||||||
|
VipsImage *imageRGB;
|
||||||
|
if (vips_extract_band(image, &imageRGB, 0, "n", image->Bands - 1, NULL))
|
||||||
|
return -1;
|
||||||
|
vips_object_local(context, imageRGB);
|
||||||
|
|
||||||
|
VipsImage *imageAlpha;
|
||||||
|
if (vips_extract_band(image, &imageAlpha, image->Bands - 1, "n", 1, NULL))
|
||||||
|
return -1;
|
||||||
|
vips_object_local(context, imageAlpha);
|
||||||
|
|
||||||
|
VipsImage *imageAlphaNormalized;
|
||||||
|
if (vips_linear1(imageAlpha, &imageAlphaNormalized, 1.0 / 255.0, 0.0, NULL))
|
||||||
|
return -1;
|
||||||
|
vips_object_local(context, imageAlphaNormalized);
|
||||||
|
|
||||||
|
VipsImage *imageRGBPremultiplied;
|
||||||
|
if (vips_multiply(imageRGB, imageAlphaNormalized, &imageRGBPremultiplied, NULL))
|
||||||
|
return -1;
|
||||||
|
vips_object_local(context, imageRGBPremultiplied);
|
||||||
|
|
||||||
|
return vips_bandjoin2(imageRGBPremultiplied, imageAlpha, out, NULL);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Unpremultiply alpha channel of `image`.
|
||||||
|
*/
|
||||||
|
int Unpremultiply(VipsObject *context, VipsImage *image, VipsImage **out) {
|
||||||
|
#if (VIPS_MAJOR_VERSION >= 9 || (VIPS_MAJOR_VERSION >= 8 && VIPS_MINOR_VERSION >= 1))
|
||||||
|
return vips_unpremultiply(image, out, NULL);
|
||||||
|
#else
|
||||||
|
VipsImage *imageRGBPremultipliedTransformed;
|
||||||
|
if (vips_extract_band(image, &imageRGBPremultipliedTransformed, 0, "n", image->Bands - 1, NULL))
|
||||||
|
return -1;
|
||||||
|
vips_object_local(context, imageRGBPremultipliedTransformed);
|
||||||
|
|
||||||
|
VipsImage *imageAlphaTransformed;
|
||||||
|
if (vips_extract_band(image, &imageAlphaTransformed, image->Bands - 1, "n", 1, NULL))
|
||||||
|
return -1;
|
||||||
|
vips_object_local(context, imageAlphaTransformed);
|
||||||
|
|
||||||
|
VipsImage *imageAlphaNormalizedTransformed;
|
||||||
|
if (vips_linear1(imageAlphaTransformed, &imageAlphaNormalizedTransformed, 1.0 / 255.0, 0.0, NULL))
|
||||||
|
return -1;
|
||||||
|
vips_object_local(context, imageAlphaNormalizedTransformed);
|
||||||
|
|
||||||
|
VipsImage *imageRGBUnpremultipliedTransformed;
|
||||||
|
if (vips_divide(imageRGBPremultipliedTransformed, imageAlphaNormalizedTransformed, &imageRGBUnpremultipliedTransformed, NULL))
|
||||||
|
return -1;
|
||||||
|
vips_object_local(context, imageRGBUnpremultipliedTransformed);
|
||||||
|
|
||||||
|
return vips_bandjoin2(imageRGBUnpremultipliedTransformed, imageAlphaTransformed, out, NULL);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Stretch luminance to cover full dynamic range.
|
||||||
|
*/
|
||||||
|
int Normalize(VipsObject *context, VipsImage *image, VipsImage **out) {
|
||||||
|
#ifndef _WIN32
|
||||||
|
// Get original colourspace
|
||||||
|
VipsInterpretation typeBeforeNormalize = image->Type;
|
||||||
|
if (typeBeforeNormalize == VIPS_INTERPRETATION_RGB) {
|
||||||
|
typeBeforeNormalize = VIPS_INTERPRETATION_sRGB;
|
||||||
|
}
|
||||||
|
// Convert to LAB colourspace
|
||||||
|
VipsImage *lab;
|
||||||
|
if (vips_colourspace(image, &lab, VIPS_INTERPRETATION_LAB, NULL)) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
vips_object_local(context, lab);
|
||||||
|
// Extract luminance
|
||||||
|
VipsImage *luminance;
|
||||||
|
if (vips_extract_band(lab, &luminance, 0, "n", 1, NULL)) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
vips_object_local(context, luminance);
|
||||||
|
// Extract chroma
|
||||||
|
VipsImage *chroma;
|
||||||
|
if (vips_extract_band(lab, &chroma, 1, "n", 2, NULL)) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
vips_object_local(context, chroma);
|
||||||
|
// Find luminance range
|
||||||
|
VipsImage *stats;
|
||||||
|
if (vips_stats(luminance, &stats, NULL)) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
vips_object_local(context, stats);
|
||||||
|
double min = *VIPS_MATRIX(stats, 0, 0);
|
||||||
|
double max = *VIPS_MATRIX(stats, 1, 0);
|
||||||
|
if (min != max) {
|
||||||
|
double f = 100.0 / (max - min);
|
||||||
|
double a = -(min * f);
|
||||||
|
// Scale luminance
|
||||||
|
VipsImage *luminance100;
|
||||||
|
if (vips_linear1(luminance, &luminance100, f, a, NULL)) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
vips_object_local(context, luminance100);
|
||||||
|
// Join scaled luminance to chroma
|
||||||
|
VipsImage *normalizedLab;
|
||||||
|
if (vips_bandjoin2(luminance100, chroma, &normalizedLab, NULL)) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
vips_object_local(context, normalizedLab);
|
||||||
|
// Convert to original colourspace
|
||||||
|
VipsImage *normalized;
|
||||||
|
if (vips_colourspace(normalizedLab, &normalized, typeBeforeNormalize, NULL)) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
vips_object_local(context, normalized);
|
||||||
|
// Attach original alpha channel, if any
|
||||||
|
if (HasAlpha(image)) {
|
||||||
|
// Extract original alpha channel
|
||||||
|
VipsImage *alpha;
|
||||||
|
if (vips_extract_band(image, &alpha, image->Bands - 1, "n", 1, NULL)) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
vips_object_local(context, alpha);
|
||||||
|
// Join alpha channel to normalised image
|
||||||
|
VipsImage *normalizedAlpha;
|
||||||
|
if (vips_bandjoin2(normalized, alpha, &normalizedAlpha, NULL)) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
vips_object_local(context, normalizedAlpha);
|
||||||
|
*out = normalizedAlpha;
|
||||||
|
} else {
|
||||||
|
*out = normalized;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Cannot normalise zero-range image
|
||||||
|
*out = image;
|
||||||
|
}
|
||||||
|
#else
|
||||||
|
// The normalize operation is currently unsupported on Windows
|
||||||
|
// See https://github.com/lovell/sharp/issues/152
|
||||||
|
*out = image;
|
||||||
|
#endif
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Gaussian blur (use sigma <0 for fast blur)
|
||||||
|
*/
|
||||||
|
int Blur(VipsObject *context, VipsImage *image, VipsImage **out, double sigma) {
|
||||||
|
VipsImage *blurred;
|
||||||
|
if (sigma < 0.0) {
|
||||||
|
// Fast, mild blur - averages neighbouring pixels
|
||||||
|
VipsImage *blur = vips_image_new_matrixv(3, 3,
|
||||||
|
1.0, 1.0, 1.0,
|
||||||
|
1.0, 1.0, 1.0,
|
||||||
|
1.0, 1.0, 1.0);
|
||||||
|
vips_image_set_double(blur, "scale", 9);
|
||||||
|
vips_object_local(context, blur);
|
||||||
|
if (vips_conv(image, &blurred, blur, NULL)) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Slower, accurate Gaussian blur
|
||||||
|
// Create Gaussian function for standard deviation
|
||||||
|
VipsImage *gaussian;
|
||||||
|
if (vips_gaussmat(&gaussian, sigma, 0.2, "separable", TRUE, "integer", TRUE, NULL)) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
vips_object_local(context, gaussian);
|
||||||
|
// Apply Gaussian function
|
||||||
|
if (vips_convsep(image, &blurred, gaussian, "precision", VIPS_PRECISION_INTEGER, NULL)) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
vips_object_local(context, blurred);
|
||||||
|
*out = blurred;
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Sharpen flat and jagged areas. Use radius of -1 for fast sharpen.
|
||||||
|
*/
|
||||||
|
int Sharpen(VipsObject *context, VipsImage *image, VipsImage **out, int radius, double flat, double jagged) {
|
||||||
|
VipsImage *sharpened;
|
||||||
|
if (radius == -1) {
|
||||||
|
// Fast, mild sharpen
|
||||||
|
VipsImage *sharpen = vips_image_new_matrixv(3, 3,
|
||||||
|
-1.0, -1.0, -1.0,
|
||||||
|
-1.0, 32.0, -1.0,
|
||||||
|
-1.0, -1.0, -1.0);
|
||||||
|
vips_image_set_double(sharpen, "scale", 24);
|
||||||
|
vips_object_local(context, sharpen);
|
||||||
|
if (vips_conv(image, &sharpened, sharpen, NULL)) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Slow, accurate sharpen in LAB colour space, with control over flat vs jagged areas
|
||||||
|
if (vips_sharpen(image, &sharpened, "radius", radius, "m1", flat, "m2", jagged, NULL)) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
vips_object_local(context, sharpened);
|
||||||
|
*out = sharpened;
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
} // namespace sharp
|
||||||
39
src/operations.h
Executable file
@@ -0,0 +1,39 @@
|
|||||||
|
#ifndef SRC_OPERATIONS_H_
|
||||||
|
#define SRC_OPERATIONS_H_
|
||||||
|
|
||||||
|
namespace sharp {
|
||||||
|
|
||||||
|
/*
|
||||||
|
Composite images `src` and `dst` with premultiplied alpha channel and output
|
||||||
|
image with premultiplied alpha.
|
||||||
|
*/
|
||||||
|
int Composite(VipsObject *context, VipsImage *src, VipsImage *dst, VipsImage **out);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Premultiply alpha channel of `image`.
|
||||||
|
*/
|
||||||
|
int Premultiply(VipsObject *context, VipsImage *image, VipsImage **out);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Unpremultiply alpha channel of `image`.
|
||||||
|
*/
|
||||||
|
int Unpremultiply(VipsObject *context, VipsImage *image, VipsImage **out);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Stretch luminance to cover full dynamic range.
|
||||||
|
*/
|
||||||
|
int Normalize(VipsObject *context, VipsImage *image, VipsImage **out);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Gaussian blur. Use sigma of -1 for fast blur.
|
||||||
|
*/
|
||||||
|
int Blur(VipsObject *context, VipsImage *image, VipsImage **out, double sigma);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Sharpen flat and jagged areas. Use radius of -1 for fast sharpen.
|
||||||
|
*/
|
||||||
|
int Sharpen(VipsObject *context, VipsImage *image, VipsImage **out, int radius, double flat, double jagged);
|
||||||
|
|
||||||
|
} // namespace sharp
|
||||||
|
|
||||||
|
#endif // SRC_OPERATIONS_H_
|
||||||
8
src/pipeline.h
Executable file
@@ -0,0 +1,8 @@
|
|||||||
|
#ifndef SRC_PIPELINE_H_
|
||||||
|
#define SRC_PIPELINE_H_
|
||||||
|
|
||||||
|
#include "nan.h"
|
||||||
|
|
||||||
|
NAN_METHOD(pipeline);
|
||||||
|
|
||||||
|
#endif // SRC_PIPELINE_H_
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
#ifndef SHARP_RESIZE_H
|
|
||||||
#define SHARP_RESIZE_H
|
|
||||||
|
|
||||||
#include "nan.h"
|
|
||||||
|
|
||||||
NAN_METHOD(resize);
|
|
||||||
|
|
||||||
#endif
|
|
||||||
21
src/sharp.cc
@@ -5,35 +5,26 @@
|
|||||||
|
|
||||||
#include "common.h"
|
#include "common.h"
|
||||||
#include "metadata.h"
|
#include "metadata.h"
|
||||||
#include "resize.h"
|
#include "pipeline.h"
|
||||||
#include "utilities.h"
|
#include "utilities.h"
|
||||||
|
|
||||||
using namespace v8;
|
extern "C" void init(v8::Handle<v8::Object> target) {
|
||||||
|
|
||||||
static void at_exit(void* arg) {
|
|
||||||
NanScope();
|
|
||||||
vips_shutdown();
|
|
||||||
}
|
|
||||||
|
|
||||||
extern "C" void init(Handle<Object> target) {
|
|
||||||
NanScope();
|
NanScope();
|
||||||
vips_init("sharp");
|
vips_init("sharp");
|
||||||
node::AtExit(at_exit);
|
|
||||||
|
|
||||||
// Set libvips operation cache limits
|
// Set libvips operation cache limits
|
||||||
vips_cache_set_max_mem(100 * 1048576); // 100 MB
|
vips_cache_set_max_mem(100 * 1024 * 1024); // 100 MB
|
||||||
vips_cache_set_max(500); // 500 operations
|
vips_cache_set_max(500); // 500 operations
|
||||||
|
|
||||||
// Notify the V8 garbage collector of max cache size
|
|
||||||
NanAdjustExternalMemory(vips_cache_get_max_mem());
|
|
||||||
|
|
||||||
// Methods available to JavaScript
|
// Methods available to JavaScript
|
||||||
NODE_SET_METHOD(target, "metadata", metadata);
|
NODE_SET_METHOD(target, "metadata", metadata);
|
||||||
NODE_SET_METHOD(target, "resize", resize);
|
NODE_SET_METHOD(target, "pipeline", pipeline);
|
||||||
NODE_SET_METHOD(target, "cache", cache);
|
NODE_SET_METHOD(target, "cache", cache);
|
||||||
NODE_SET_METHOD(target, "concurrency", concurrency);
|
NODE_SET_METHOD(target, "concurrency", concurrency);
|
||||||
NODE_SET_METHOD(target, "counters", counters);
|
NODE_SET_METHOD(target, "counters", counters);
|
||||||
NODE_SET_METHOD(target, "libvipsVersion", libvipsVersion);
|
NODE_SET_METHOD(target, "libvipsVersion", libvipsVersion);
|
||||||
|
NODE_SET_METHOD(target, "format", format);
|
||||||
|
NODE_SET_METHOD(target, "_maxColourDistance", _maxColourDistance);
|
||||||
}
|
}
|
||||||
|
|
||||||
NODE_MODULE(sharp, init)
|
NODE_MODULE(sharp, init)
|
||||||
|
|||||||
182
src/utilities.cc
@@ -4,10 +4,14 @@
|
|||||||
#include "nan.h"
|
#include "nan.h"
|
||||||
|
|
||||||
#include "common.h"
|
#include "common.h"
|
||||||
|
#include "operations.h"
|
||||||
#include "utilities.h"
|
#include "utilities.h"
|
||||||
|
|
||||||
using namespace v8;
|
using v8::Local;
|
||||||
using namespace sharp;
|
using v8::Object;
|
||||||
|
using v8::Number;
|
||||||
|
using v8::String;
|
||||||
|
using v8::Boolean;
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Get and set cache memory and item limits
|
Get and set cache memory and item limits
|
||||||
@@ -57,6 +61,9 @@ NAN_METHOD(concurrency) {
|
|||||||
Get internal counters (queued tasks, processing tasks)
|
Get internal counters (queued tasks, processing tasks)
|
||||||
*/
|
*/
|
||||||
NAN_METHOD(counters) {
|
NAN_METHOD(counters) {
|
||||||
|
using sharp::counterProcess;
|
||||||
|
using sharp::counterQueue;
|
||||||
|
|
||||||
NanScope();
|
NanScope();
|
||||||
Local<Object> counters = NanNew<Object>();
|
Local<Object> counters = NanNew<Object>();
|
||||||
counters->Set(NanNew<String>("queue"), NanNew<Number>(counterQueue));
|
counters->Set(NanNew<String>("queue"), NanNew<Number>(counterQueue));
|
||||||
@@ -70,6 +77,175 @@ NAN_METHOD(counters) {
|
|||||||
NAN_METHOD(libvipsVersion) {
|
NAN_METHOD(libvipsVersion) {
|
||||||
NanScope();
|
NanScope();
|
||||||
char version[9];
|
char version[9];
|
||||||
snprintf(version, 9, "%d.%d.%d", vips_version(0), vips_version(1), vips_version(2));
|
g_snprintf(version, sizeof(version), "%d.%d.%d", vips_version(0), vips_version(1), vips_version(2));
|
||||||
NanReturnValue(NanNew<String>(version));
|
NanReturnValue(NanNew<String>(version));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
Get available input/output file/buffer/stream formats
|
||||||
|
*/
|
||||||
|
NAN_METHOD(format) {
|
||||||
|
NanScope();
|
||||||
|
|
||||||
|
// Attribute names
|
||||||
|
Local<String> attrId = NanNew<String>("id");
|
||||||
|
Local<String> attrInput = NanNew<String>("input");
|
||||||
|
Local<String> attrOutput = NanNew<String>("output");
|
||||||
|
Local<String> attrFile = NanNew<String>("file");
|
||||||
|
Local<String> attrBuffer = NanNew<String>("buffer");
|
||||||
|
Local<String> attrStream = NanNew<String>("stream");
|
||||||
|
|
||||||
|
// Which load/save operations are available for each compressed format?
|
||||||
|
Local<Object> format = NanNew<Object>();
|
||||||
|
for (std::string f : {"jpeg", "png", "webp", "tiff", "magick", "openslide", "dz"}) {
|
||||||
|
// Input
|
||||||
|
Local<Object> input = NanNew<Object>();
|
||||||
|
input->Set(attrFile, NanNew<Boolean>(
|
||||||
|
vips_type_find("VipsOperation", (f + "load").c_str())));
|
||||||
|
input->Set(attrBuffer, NanNew<Boolean>(
|
||||||
|
vips_type_find("VipsOperation", (f + "load_buffer").c_str())));
|
||||||
|
input->Set(attrStream, input->Get(attrBuffer));
|
||||||
|
// Output
|
||||||
|
Local<Object> output = NanNew<Object>();
|
||||||
|
output->Set(attrFile, NanNew<Boolean>(
|
||||||
|
vips_type_find("VipsOperation", (f + "save").c_str())));
|
||||||
|
output->Set(attrBuffer, NanNew<Boolean>(
|
||||||
|
vips_type_find("VipsOperation", (f + "save_buffer").c_str())));
|
||||||
|
output->Set(attrStream, output->Get(attrBuffer));
|
||||||
|
// Other attributes
|
||||||
|
Local<Object> container = NanNew<Object>();
|
||||||
|
Local<String> formatId = NanNew<String>(f);
|
||||||
|
container->Set(attrId, formatId);
|
||||||
|
container->Set(attrInput, input);
|
||||||
|
container->Set(attrOutput, output);
|
||||||
|
// Add to set of formats
|
||||||
|
format->Set(formatId, container);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Raw, uncompressed data
|
||||||
|
Local<Object> raw = NanNew<Object>();
|
||||||
|
raw->Set(attrId, NanNew<String>("raw"));
|
||||||
|
format->Set(NanNew<String>("raw"), raw);
|
||||||
|
// No support for raw input yet, so always false
|
||||||
|
Local<Boolean> unsupported = NanNew<Boolean>(false);
|
||||||
|
Local<Object> rawInput = NanNew<Object>();
|
||||||
|
rawInput->Set(attrFile, unsupported);
|
||||||
|
rawInput->Set(attrBuffer, unsupported);
|
||||||
|
rawInput->Set(attrStream, unsupported);
|
||||||
|
raw->Set(attrInput, rawInput);
|
||||||
|
// Raw output via Buffer/Stream is available in libvips >= 7.42.0
|
||||||
|
Local<Boolean> supportsRawOutput = NanNew<Boolean>(vips_version(0) >= 8 || (vips_version(0) == 7 && vips_version(1) >= 42));
|
||||||
|
Local<Object> rawOutput = NanNew<Object>();
|
||||||
|
rawOutput->Set(attrFile, unsupported);
|
||||||
|
rawOutput->Set(attrBuffer, supportsRawOutput);
|
||||||
|
rawOutput->Set(attrStream, supportsRawOutput);
|
||||||
|
raw->Set(attrOutput, rawOutput);
|
||||||
|
|
||||||
|
NanReturnValue(format);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
Synchronous, internal-only method used by some of the functional tests.
|
||||||
|
Calculates the maximum colour distance using the DE2000 algorithm
|
||||||
|
between two images of the same dimensions and number of channels.
|
||||||
|
*/
|
||||||
|
NAN_METHOD(_maxColourDistance) {
|
||||||
|
using sharp::Premultiply;
|
||||||
|
using sharp::DetermineImageType;
|
||||||
|
using sharp::ImageType;
|
||||||
|
using sharp::InitImage;
|
||||||
|
using sharp::HasAlpha;
|
||||||
|
|
||||||
|
NanScope();
|
||||||
|
|
||||||
|
// Create "hook" VipsObject to hang image references from
|
||||||
|
VipsObject *hook = reinterpret_cast<VipsObject*>(vips_image_new());
|
||||||
|
|
||||||
|
// Open input files
|
||||||
|
VipsImage *image1 = NULL;
|
||||||
|
ImageType imageType1 = DetermineImageType(*String::Utf8Value(args[0]));
|
||||||
|
if (imageType1 != ImageType::UNKNOWN) {
|
||||||
|
image1 = InitImage(*String::Utf8Value(args[0]), VIPS_ACCESS_SEQUENTIAL);
|
||||||
|
if (image1 == NULL) {
|
||||||
|
g_object_unref(hook);
|
||||||
|
return NanThrowError("Input file 1 has corrupt header");
|
||||||
|
} else {
|
||||||
|
vips_object_local(hook, image1);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
g_object_unref(hook);
|
||||||
|
return NanThrowError("Input file 1 is of an unsupported image format");
|
||||||
|
}
|
||||||
|
VipsImage *image2 = NULL;
|
||||||
|
ImageType imageType2 = DetermineImageType(*String::Utf8Value(args[1]));
|
||||||
|
if (imageType2 != ImageType::UNKNOWN) {
|
||||||
|
image2 = InitImage(*String::Utf8Value(args[1]), VIPS_ACCESS_SEQUENTIAL);
|
||||||
|
if (image2 == NULL) {
|
||||||
|
g_object_unref(hook);
|
||||||
|
return NanThrowError("Input file 2 has corrupt header");
|
||||||
|
} else {
|
||||||
|
vips_object_local(hook, image2);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
g_object_unref(hook);
|
||||||
|
return NanThrowError("Input file 2 is of an unsupported image format");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ensure same number of channels
|
||||||
|
if (image1->Bands != image2->Bands) {
|
||||||
|
g_object_unref(hook);
|
||||||
|
return NanThrowError("mismatchedBands");
|
||||||
|
}
|
||||||
|
// Ensure same dimensions
|
||||||
|
if (image1->Xsize != image2->Xsize || image1->Ysize != image2->Ysize) {
|
||||||
|
g_object_unref(hook);
|
||||||
|
return NanThrowError("mismatchedDimensions");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Premultiply and remove alpha
|
||||||
|
if (HasAlpha(image1)) {
|
||||||
|
VipsImage *imagePremultiplied1;
|
||||||
|
if (Premultiply(hook, image1, &imagePremultiplied1)) {
|
||||||
|
g_object_unref(hook);
|
||||||
|
return NanThrowError(vips_error_buffer());
|
||||||
|
}
|
||||||
|
vips_object_local(hook, imagePremultiplied1);
|
||||||
|
VipsImage *imagePremultipliedNoAlpha1;
|
||||||
|
if (vips_extract_band(image1, &imagePremultipliedNoAlpha1, 1, "n", image1->Bands - 1, NULL)) {
|
||||||
|
g_object_unref(hook);
|
||||||
|
return NanThrowError(vips_error_buffer());
|
||||||
|
}
|
||||||
|
vips_object_local(hook, imagePremultipliedNoAlpha1);
|
||||||
|
image1 = imagePremultipliedNoAlpha1;
|
||||||
|
}
|
||||||
|
if (HasAlpha(image2)) {
|
||||||
|
VipsImage *imagePremultiplied2;
|
||||||
|
if (Premultiply(hook, image2, &imagePremultiplied2)) {
|
||||||
|
g_object_unref(hook);
|
||||||
|
return NanThrowError(vips_error_buffer());
|
||||||
|
}
|
||||||
|
vips_object_local(hook, imagePremultiplied2);
|
||||||
|
VipsImage *imagePremultipliedNoAlpha2;
|
||||||
|
if (vips_extract_band(image2, &imagePremultipliedNoAlpha2, 1, "n", image2->Bands - 1, NULL)) {
|
||||||
|
g_object_unref(hook);
|
||||||
|
return NanThrowError(vips_error_buffer());
|
||||||
|
}
|
||||||
|
vips_object_local(hook, imagePremultipliedNoAlpha2);
|
||||||
|
image2 = imagePremultipliedNoAlpha2;
|
||||||
|
}
|
||||||
|
// Calculate colour distance
|
||||||
|
VipsImage *difference;
|
||||||
|
if (vips_dE00(image1, image2, &difference, NULL)) {
|
||||||
|
g_object_unref(hook);
|
||||||
|
return NanThrowError(vips_error_buffer());
|
||||||
|
}
|
||||||
|
vips_object_local(hook, difference);
|
||||||
|
// Extract maximum distance
|
||||||
|
double maxColourDistance;
|
||||||
|
if (vips_max(difference, &maxColourDistance, NULL)) {
|
||||||
|
g_object_unref(hook);
|
||||||
|
return NanThrowError(vips_error_buffer());
|
||||||
|
}
|
||||||
|
g_object_unref(hook);
|
||||||
|
NanReturnValue(maxColourDistance);
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
#ifndef SHARP_UTILITIES_H
|
#ifndef SRC_UTILITIES_H_
|
||||||
#define SHARP_UTILITIES_H
|
#define SRC_UTILITIES_H_
|
||||||
|
|
||||||
#include "nan.h"
|
#include "nan.h"
|
||||||
|
|
||||||
@@ -7,5 +7,7 @@ NAN_METHOD(cache);
|
|||||||
NAN_METHOD(concurrency);
|
NAN_METHOD(concurrency);
|
||||||
NAN_METHOD(counters);
|
NAN_METHOD(counters);
|
||||||
NAN_METHOD(libvipsVersion);
|
NAN_METHOD(libvipsVersion);
|
||||||
|
NAN_METHOD(format);
|
||||||
|
NAN_METHOD(_maxColourDistance);
|
||||||
|
|
||||||
#endif
|
#endif // SRC_UTILITIES_H_
|
||||||
|
|||||||
@@ -9,13 +9,14 @@
|
|||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"imagemagick": "^0.1.3",
|
"imagemagick": "^0.1.3",
|
||||||
"imagemagick-native": "^1.6.0",
|
"imagemagick-native": "^1.8.0",
|
||||||
"gm": "^1.17.0",
|
"gm": "^1.18.1",
|
||||||
"async": "^0.9.0",
|
"lwip": "^0.0.7",
|
||||||
"semver": "^4.1.0",
|
"async": "^1.4.2",
|
||||||
|
"semver": "^5.0.1",
|
||||||
"benchmark": "^1.0.0"
|
"benchmark": "^1.0.0"
|
||||||
},
|
},
|
||||||
"license": "Apache 2.0",
|
"license": "Apache-2.0",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=0.10"
|
"node": ">=0.10"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ var semver = require('semver');
|
|||||||
var imagemagick = require('imagemagick');
|
var imagemagick = require('imagemagick');
|
||||||
var imagemagickNative = require('imagemagick-native');
|
var imagemagickNative = require('imagemagick-native');
|
||||||
var gm = require('gm');
|
var gm = require('gm');
|
||||||
|
var lwip = require('lwip');
|
||||||
var sharp = require('../../index');
|
var sharp = require('../../index');
|
||||||
|
|
||||||
var fixtures = require('../fixtures');
|
var fixtures = require('../fixtures');
|
||||||
@@ -26,7 +27,48 @@ sharp.cache(0);
|
|||||||
async.series({
|
async.series({
|
||||||
jpeg: function(callback) {
|
jpeg: function(callback) {
|
||||||
var inputJpgBuffer = fs.readFileSync(fixtures.inputJpg);
|
var inputJpgBuffer = fs.readFileSync(fixtures.inputJpg);
|
||||||
(new Benchmark.Suite('jpeg')).add('imagemagick-file-file', {
|
(new Benchmark.Suite('jpeg')).add('lwip-file-file', {
|
||||||
|
defer: true,
|
||||||
|
fn: function(deferred) {
|
||||||
|
lwip.open(fixtures.inputJpg, function (err, image) {
|
||||||
|
if (err) {
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
image.resize(width, height, 'linear', function (err, image) {
|
||||||
|
if (err) {
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
image.writeFile(fixtures.outputJpg, {quality: 80}, function (err) {
|
||||||
|
if (err) {
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
deferred.resolve();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}).add('lwip-buffer-buffer', {
|
||||||
|
defer: true,
|
||||||
|
fn: function(deferred) {
|
||||||
|
lwip.open(inputJpgBuffer, 'jpg', function (err, image) {
|
||||||
|
if (err) {
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
image.resize(width, height, 'linear', function (err, image) {
|
||||||
|
if (err) {
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
image.toBuffer('jpg', {quality: 80}, function (err, buffer) {
|
||||||
|
if (err) {
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
assert.notStrictEqual(null, buffer);
|
||||||
|
deferred.resolve();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}).add('imagemagick-file-file', {
|
||||||
defer: true,
|
defer: true,
|
||||||
fn: function(deferred) {
|
fn: function(deferred) {
|
||||||
imagemagick.resize({
|
imagemagick.resize({
|
||||||
@@ -311,6 +353,18 @@ async.series({
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
}).add('sharp-normalise', {
|
||||||
|
defer: true,
|
||||||
|
fn: function(deferred) {
|
||||||
|
sharp(inputJpgBuffer).resize(width, height).normalise().toBuffer(function(err, buffer) {
|
||||||
|
if (err) {
|
||||||
|
throw err;
|
||||||
|
} else {
|
||||||
|
assert.notStrictEqual(null, buffer);
|
||||||
|
deferred.resolve();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
}).add('sharp-greyscale', {
|
}).add('sharp-greyscale', {
|
||||||
defer: true,
|
defer: true,
|
||||||
fn: function(deferred) {
|
fn: function(deferred) {
|
||||||
@@ -347,6 +401,18 @@ async.series({
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
}).add('sharp-without-chroma-subsampling', {
|
||||||
|
defer: true,
|
||||||
|
fn: function(deferred) {
|
||||||
|
sharp(inputJpgBuffer).resize(width, height).withoutChromaSubsampling().toBuffer(function(err, buffer) {
|
||||||
|
if (err) {
|
||||||
|
throw err;
|
||||||
|
} else {
|
||||||
|
assert.notStrictEqual(null, buffer);
|
||||||
|
deferred.resolve();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
}).add('sharp-rotate', {
|
}).add('sharp-rotate', {
|
||||||
defer: true,
|
defer: true,
|
||||||
fn: function(deferred) {
|
fn: function(deferred) {
|
||||||
@@ -380,7 +446,28 @@ async.series({
|
|||||||
png: function(callback) {
|
png: function(callback) {
|
||||||
var inputPngBuffer = fs.readFileSync(fixtures.inputPng);
|
var inputPngBuffer = fs.readFileSync(fixtures.inputPng);
|
||||||
var pngSuite = new Benchmark.Suite('png');
|
var pngSuite = new Benchmark.Suite('png');
|
||||||
pngSuite.add('imagemagick-file-file', {
|
pngSuite.add('lwip-buffer-buffer', {
|
||||||
|
defer: true,
|
||||||
|
fn: function(deferred) {
|
||||||
|
lwip.open(inputPngBuffer, 'png', function (err, image) {
|
||||||
|
if (err) {
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
image.resize(width, height, 'linear', function (err, image) {
|
||||||
|
if (err) {
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
image.toBuffer('png', function (err, buffer) {
|
||||||
|
if (err) {
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
assert.notStrictEqual(null, buffer);
|
||||||
|
deferred.resolve();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}).add('imagemagick-file-file', {
|
||||||
defer: true,
|
defer: true,
|
||||||
fn: function(deferred) {
|
fn: function(deferred) {
|
||||||
imagemagick.resize({
|
imagemagick.resize({
|
||||||
@@ -388,7 +475,6 @@ async.series({
|
|||||||
dstPath: fixtures.outputPng,
|
dstPath: fixtures.outputPng,
|
||||||
width: width,
|
width: width,
|
||||||
height: height,
|
height: height,
|
||||||
format: 'jpg',
|
|
||||||
filter: magickFilter
|
filter: magickFilter
|
||||||
}, function(err) {
|
}, function(err) {
|
||||||
if (err) {
|
if (err) {
|
||||||
|
|||||||
@@ -11,8 +11,11 @@ var fixtures = require('../fixtures');
|
|||||||
var min = 320;
|
var min = 320;
|
||||||
var max = 960;
|
var max = 960;
|
||||||
|
|
||||||
|
// Nearest equivalent to bilinear
|
||||||
|
var magickFilter = 'Triangle';
|
||||||
|
|
||||||
var randomDimension = function() {
|
var randomDimension = function() {
|
||||||
return Math.random() * (max - min) + min;
|
return Math.ceil(Math.random() * (max - min) + min);
|
||||||
};
|
};
|
||||||
|
|
||||||
new Benchmark.Suite('random').add('imagemagick', {
|
new Benchmark.Suite('random').add('imagemagick', {
|
||||||
@@ -23,7 +26,9 @@ new Benchmark.Suite('random').add('imagemagick', {
|
|||||||
dstPath: fixtures.outputJpg,
|
dstPath: fixtures.outputJpg,
|
||||||
quality: 0.8,
|
quality: 0.8,
|
||||||
width: randomDimension(),
|
width: randomDimension(),
|
||||||
height: randomDimension()
|
height: randomDimension(),
|
||||||
|
format: 'jpg',
|
||||||
|
filter: magickFilter
|
||||||
}, function(err) {
|
}, function(err) {
|
||||||
if (err) {
|
if (err) {
|
||||||
throw err;
|
throw err;
|
||||||
@@ -35,14 +40,18 @@ new Benchmark.Suite('random').add('imagemagick', {
|
|||||||
}).add('gm', {
|
}).add('gm', {
|
||||||
defer: true,
|
defer: true,
|
||||||
fn: function(deferred) {
|
fn: function(deferred) {
|
||||||
gm(fixtures.inputJpg).resize(randomDimension(), randomDimension()).quality(80).toBuffer(function (err, buffer) {
|
gm(fixtures.inputJpg)
|
||||||
if (err) {
|
.resize(randomDimension(), randomDimension())
|
||||||
throw err;
|
.filter(magickFilter)
|
||||||
} else {
|
.quality(80)
|
||||||
assert.notStrictEqual(null, buffer);
|
.toBuffer(function (err, buffer) {
|
||||||
deferred.resolve();
|
if (err) {
|
||||||
}
|
throw err;
|
||||||
});
|
} else {
|
||||||
|
assert.notStrictEqual(null, buffer);
|
||||||
|
deferred.resolve();
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}).add('sharp', {
|
}).add('sharp', {
|
||||||
defer: true,
|
defer: true,
|
||||||
|
|||||||
BIN
test/fixtures/2x2_fdcce6.png
vendored
Normal file
|
After Width: | Height: | Size: 76 B |
BIN
test/fixtures/5_webp_a.webp
vendored
Normal file
|
After Width: | Height: | Size: 68 KiB |
BIN
test/fixtures/CMU-1-Small-Region.svs
vendored
Normal file
BIN
test/fixtures/alpha-layer-0-background.png
vendored
Normal file
|
After Width: | Height: | Size: 136 KiB |
BIN
test/fixtures/alpha-layer-1-fill-low-alpha.png
vendored
Normal file
|
After Width: | Height: | Size: 222 KiB |
BIN
test/fixtures/alpha-layer-1-fill.png
vendored
Normal file
|
After Width: | Height: | Size: 260 KiB |
BIN
test/fixtures/alpha-layer-2-ink-low-alpha.png
vendored
Normal file
|
After Width: | Height: | Size: 89 KiB |
BIN
test/fixtures/alpha-layer-2-ink.png
vendored
Normal file
|
After Width: | Height: | Size: 80 KiB |
BIN
test/fixtures/alpha-premultiply-1024x768-paper.png
vendored
Normal file
|
After Width: | Height: | Size: 255 KiB |
BIN
test/fixtures/alpha-premultiply-2048x1536-paper.png
vendored
Normal file
|
After Width: | Height: | Size: 640 KiB |
BIN
test/fixtures/corrupt-header.jpg
vendored
Normal file
|
After Width: | Height: | Size: 1.0 KiB |
BIN
test/fixtures/expected/alpha-layer-01-imagemagick.png
vendored
Normal file
|
After Width: | Height: | Size: 234 KiB |
BIN
test/fixtures/expected/alpha-layer-01-low-alpha-imagemagick.png
vendored
Normal file
|
After Width: | Height: | Size: 186 KiB |
BIN
test/fixtures/expected/alpha-layer-01-low-alpha.png
vendored
Normal file
|
After Width: | Height: | Size: 188 KiB |
BIN
test/fixtures/expected/alpha-layer-01.png
vendored
Normal file
|
After Width: | Height: | Size: 234 KiB |
BIN
test/fixtures/expected/alpha-layer-012-imagemagick.png
vendored
Normal file
|
After Width: | Height: | Size: 259 KiB |
BIN
test/fixtures/expected/alpha-layer-012-low-alpha-imagemagick.png
vendored
Normal file
|
After Width: | Height: | Size: 208 KiB |
BIN
test/fixtures/expected/alpha-layer-012-low-alpha.png
vendored
Normal file
|
After Width: | Height: | Size: 209 KiB |
BIN
test/fixtures/expected/alpha-layer-012.png
vendored
Normal file
|
After Width: | Height: | Size: 260 KiB |
BIN
test/fixtures/expected/alpha-layer-12-imagemagick.png
vendored
Normal file
|
After Width: | Height: | Size: 221 KiB |
BIN
test/fixtures/expected/alpha-layer-12-low-alpha-imagemagick.png
vendored
Normal file
|
After Width: | Height: | Size: 179 KiB |
BIN
test/fixtures/expected/alpha-layer-12-low-alpha.png
vendored
Normal file
|
After Width: | Height: | Size: 179 KiB |
BIN
test/fixtures/expected/alpha-layer-12.png
vendored
Normal file
|
After Width: | Height: | Size: 222 KiB |
BIN
test/fixtures/expected/alpha-premultiply-enlargement-2048x1536-paper.png
vendored
Normal file
|
After Width: | Height: | Size: 922 KiB |
BIN
test/fixtures/expected/alpha-premultiply-reduction-1024x768-paper.png
vendored
Normal file
|
After Width: | Height: | Size: 208 KiB |
BIN
test/fixtures/expected/embed-enlarge.png
vendored
Normal file
|
After Width: | Height: | Size: 813 B |
BIN
test/fixtures/expected/exif-5.jpg
vendored
Normal file
|
After Width: | Height: | Size: 23 KiB |
BIN
test/fixtures/expected/exif-8.jpg
vendored
Normal file
|
After Width: | Height: | Size: 23 KiB |
BIN
test/fixtures/expected/extract-resize-crop-extract.jpg
vendored
Normal file
|
After Width: | Height: | Size: 1.1 KiB |
BIN
test/fixtures/expected/extract-resize.jpg
vendored
Normal file
|
After Width: | Height: | Size: 506 B |
BIN
test/fixtures/expected/extract-rotate.jpg
vendored
Normal file
|
After Width: | Height: | Size: 1.0 KiB |
BIN
test/fixtures/expected/extract.jpg
vendored
Normal file
|
After Width: | Height: | Size: 348 B |
BIN
test/fixtures/expected/extract.png
vendored
Normal file
|
After Width: | Height: | Size: 5.3 KiB |
BIN
test/fixtures/expected/extract.tiff
vendored
Normal file
BIN
test/fixtures/expected/extract.webp
vendored
Normal file
|
After Width: | Height: | Size: 4.7 KiB |
BIN
test/fixtures/expected/flatten-black.jpg
vendored
Normal file
|
After Width: | Height: | Size: 996 B |
BIN
test/fixtures/expected/flatten-orange.jpg
vendored
Normal file
|
After Width: | Height: | Size: 3.7 KiB |
BIN
test/fixtures/expected/flip-and-flop.jpg
vendored
Normal file
|
After Width: | Height: | Size: 15 KiB |
BIN
test/fixtures/expected/flip.jpg
vendored
Normal file
|
After Width: | Height: | Size: 15 KiB |
BIN
test/fixtures/expected/flop.jpg
vendored
Normal file
|
After Width: | Height: | Size: 15 KiB |
BIN
test/fixtures/expected/gamma-0.0.jpg
vendored
Normal file
|
After Width: | Height: | Size: 377 B |
BIN
test/fixtures/expected/gamma-2.2.jpg
vendored
Normal file
|
After Width: | Height: | Size: 2.0 KiB |
BIN
test/fixtures/expected/gamma-3.0.jpg
vendored
Normal file
|
After Width: | Height: | Size: 2.3 KiB |
BIN
test/fixtures/expected/gamma-alpha.jpg
vendored
Normal file
|
After Width: | Height: | Size: 4.1 KiB |
BIN
test/fixtures/expected/gravity-center.jpg
vendored
Normal file
|
After Width: | Height: | Size: 5.2 KiB |
BIN
test/fixtures/expected/gravity-centre.jpg
vendored
Normal file
|
After Width: | Height: | Size: 5.4 KiB |
BIN
test/fixtures/expected/gravity-east.jpg
vendored
Normal file
|
After Width: | Height: | Size: 3.8 KiB |
BIN
test/fixtures/expected/gravity-north.jpg
vendored
Normal file
|
After Width: | Height: | Size: 3.4 KiB |
BIN
test/fixtures/expected/gravity-south.jpg
vendored
Normal file
|
After Width: | Height: | Size: 5.2 KiB |
BIN
test/fixtures/expected/gravity-west.jpg
vendored
Normal file
|
After Width: | Height: | Size: 4.4 KiB |
BIN
test/fixtures/expected/overlay-jpeg-with-greyscale.jpg
vendored
Normal file
|
After Width: | Height: | Size: 17 KiB |
BIN
test/fixtures/expected/overlay-jpeg-with-rgb.jpg
vendored
Normal file
|
After Width: | Height: | Size: 230 KiB |
BIN
test/fixtures/expected/overlay-jpeg-with-webp.jpg
vendored
Normal file
|
After Width: | Height: | Size: 24 KiB |
BIN
test/fixtures/expected/resize-crop-extract.jpg
vendored
Normal file
|
After Width: | Height: | Size: 1.4 KiB |
BIN
test/fixtures/expected/rotate-extract.jpg
vendored
Normal file
|
After Width: | Height: | Size: 1.6 KiB |
BIN
test/fixtures/grey-8bit-alpha.png
vendored
Normal file
|
After Width: | Height: | Size: 23 KiB |
116
test/fixtures/index.js
vendored
@@ -1,11 +1,43 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
var path = require('path');
|
var path = require('path');
|
||||||
|
var assert = require('assert');
|
||||||
|
var sharp = require('../../index');
|
||||||
|
var maxColourDistance = require('../../build/Release/sharp')._maxColourDistance;
|
||||||
|
|
||||||
|
// Helpers
|
||||||
var getPath = function(filename) {
|
var getPath = function(filename) {
|
||||||
return path.join(__dirname, filename);
|
return path.join(__dirname, filename);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Generates a 64-bit-as-binary-string image fingerprint
|
||||||
|
// Based on the dHash gradient method - see http://www.hackerfactor.com/blog/index.php?/archives/529-Kind-of-Like-That.html
|
||||||
|
var fingerprint = function(image, callback) {
|
||||||
|
sharp(image)
|
||||||
|
.greyscale()
|
||||||
|
.normalise()
|
||||||
|
.resize(9, 8)
|
||||||
|
.ignoreAspectRatio()
|
||||||
|
.interpolateWith(sharp.interpolator.vertexSplitQuadraticBasisSpline)
|
||||||
|
.raw()
|
||||||
|
.toBuffer(function(err, data) {
|
||||||
|
if (err) {
|
||||||
|
callback(err);
|
||||||
|
} else {
|
||||||
|
var fingerprint = '';
|
||||||
|
for (var col = 0; col < 8; col++) {
|
||||||
|
var gradient = 0;
|
||||||
|
for (var row = 0; row < 8; row++) {
|
||||||
|
var left = data[row * 8 + col];
|
||||||
|
var right = data[row * 8 + col + 1];
|
||||||
|
fingerprint = fingerprint + (left < right ? '1' : '0');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
callback(null, fingerprint);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
|
|
||||||
inputJpg: getPath('2569067123_aca715a2ee_o.jpg'), // http://www.flickr.com/photos/grizdave/2569067123/
|
inputJpg: getPath('2569067123_aca715a2ee_o.jpg'), // http://www.flickr.com/photos/grizdave/2569067123/
|
||||||
@@ -14,21 +46,103 @@ module.exports = {
|
|||||||
inputJpgWithGammaHoliness: getPath('gamma_dalai_lama_gray.jpg'), // http://www.4p8.com/eric.brasseur/gamma.html
|
inputJpgWithGammaHoliness: getPath('gamma_dalai_lama_gray.jpg'), // http://www.4p8.com/eric.brasseur/gamma.html
|
||||||
inputJpgWithCmykProfile: getPath('Channel_digital_image_CMYK_color.jpg'), // http://en.wikipedia.org/wiki/File:Channel_digital_image_CMYK_color.jpg
|
inputJpgWithCmykProfile: getPath('Channel_digital_image_CMYK_color.jpg'), // http://en.wikipedia.org/wiki/File:Channel_digital_image_CMYK_color.jpg
|
||||||
inputJpgWithCmykNoProfile: getPath('Channel_digital_image_CMYK_color_no_profile.jpg'),
|
inputJpgWithCmykNoProfile: getPath('Channel_digital_image_CMYK_color_no_profile.jpg'),
|
||||||
|
inputJpgWithCorruptHeader: getPath('corrupt-header.jpg'),
|
||||||
|
inputJpgWithLowContrast: getPath('low-contrast.jpg'), // http://www.flickr.com/photos/grizdave/2569067123/
|
||||||
|
|
||||||
inputPng: getPath('50020484-00001.png'), // http://c.searspartsdirect.com/lis_png/PLDM/50020484-00001.png
|
inputPng: getPath('50020484-00001.png'), // http://c.searspartsdirect.com/lis_png/PLDM/50020484-00001.png
|
||||||
inputPngWithTransparency: getPath('blackbug.png'), // public domain
|
inputPngWithTransparency: getPath('blackbug.png'), // public domain
|
||||||
|
inputPngWithGreyAlpha: getPath('grey-8bit-alpha.png'),
|
||||||
|
inputPngWithOneColor: getPath('2x2_fdcce6.png'),
|
||||||
|
inputPngOverlayLayer0: getPath('alpha-layer-0-background.png'),
|
||||||
|
inputPngOverlayLayer1: getPath('alpha-layer-1-fill.png'),
|
||||||
|
inputPngOverlayLayer2: getPath('alpha-layer-2-ink.png'),
|
||||||
|
inputPngOverlayLayer1LowAlpha: getPath('alpha-layer-1-fill-low-alpha.png'),
|
||||||
|
inputPngOverlayLayer2LowAlpha: getPath('alpha-layer-2-ink-low-alpha.png'),
|
||||||
|
inputPngAlphaPremultiplicationSmall: getPath('alpha-premultiply-1024x768-paper.png'),
|
||||||
|
inputPngAlphaPremultiplicationLarge: getPath('alpha-premultiply-2048x1536-paper.png'),
|
||||||
|
|
||||||
inputWebP: getPath('4.webp'), // http://www.gstatic.com/webp/gallery/4.webp
|
inputWebP: getPath('4.webp'), // http://www.gstatic.com/webp/gallery/4.webp
|
||||||
|
inputWebPWithTransparency: getPath('5_webp_a.webp'), // http://www.gstatic.com/webp/gallery3/5_webp_a.webp
|
||||||
inputTiff: getPath('G31D.TIF'), // http://www.fileformat.info/format/tiff/sample/e6c9a6e5253348f4aef6d17b534360ab/index.htm
|
inputTiff: getPath('G31D.TIF'), // http://www.fileformat.info/format/tiff/sample/e6c9a6e5253348f4aef6d17b534360ab/index.htm
|
||||||
inputGif: getPath('Crash_test.gif'), // http://upload.wikimedia.org/wikipedia/commons/e/e3/Crash_test.gif
|
inputGif: getPath('Crash_test.gif'), // http://upload.wikimedia.org/wikipedia/commons/e/e3/Crash_test.gif
|
||||||
inputSvg: getPath('Wikimedia-logo.svg'), // http://commons.wikimedia.org/wiki/File:Wikimedia-logo.svg
|
inputSvg: getPath('Wikimedia-logo.svg'), // http://commons.wikimedia.org/wiki/File:Wikimedia-logo.svg
|
||||||
inputPsd: getPath('free-gearhead-pack.psd'), // https://dribbble.com/shots/1624241-Free-Gearhead-Vector-Pack
|
inputPsd: getPath('free-gearhead-pack.psd'), // https://dribbble.com/shots/1624241-Free-Gearhead-Vector-Pack
|
||||||
|
|
||||||
|
inputSvs: getPath('CMU-1-Small-Region.svs'), // http://openslide.cs.cmu.edu/download/openslide-testdata/Aperio/CMU-1-Small-Region.svs
|
||||||
|
|
||||||
outputJpg: getPath('output.jpg'),
|
outputJpg: getPath('output.jpg'),
|
||||||
outputPng: getPath('output.png'),
|
outputPng: getPath('output.png'),
|
||||||
outputWebP: getPath('output.webp'),
|
outputWebP: getPath('output.webp'),
|
||||||
outputZoinks: getPath('output.zoinks'), // an 'unknown' file extension
|
outputZoinks: getPath('output.zoinks'), // an 'unknown' file extension
|
||||||
|
|
||||||
path: getPath // allows tests to write files to fixtures directory (for testing with human eyes)
|
// Path for tests requiring human inspection
|
||||||
|
path: getPath,
|
||||||
|
|
||||||
|
// Path for expected output images
|
||||||
|
expected: function(filename) {
|
||||||
|
return getPath(path.join('expected', filename));
|
||||||
|
},
|
||||||
|
|
||||||
|
// Verify similarity of expected vs actual images via fingerprint
|
||||||
|
// Specify distance threshold using `options={threshold: 42}`, default
|
||||||
|
// `threshold` is 5;
|
||||||
|
assertSimilar: function(expectedImage, actualImage, options, callback) {
|
||||||
|
if (typeof options === 'function') {
|
||||||
|
callback = options;
|
||||||
|
options = {};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof options === 'undefined' && options === null) {
|
||||||
|
options = {};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (options.threshold === null || typeof options.threshold === 'undefined') {
|
||||||
|
options.threshold = 5; // ~7% threshold
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof options.threshold !== 'number') {
|
||||||
|
throw new TypeError('`options.threshold` must be a number');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof callback !== 'function') {
|
||||||
|
throw new TypeError('`callback` must be a function');
|
||||||
|
}
|
||||||
|
|
||||||
|
fingerprint(expectedImage, function(err, expectedFingerprint) {
|
||||||
|
if (err) return callback(err);
|
||||||
|
fingerprint(actualImage, function(err, actualFingerprint) {
|
||||||
|
if (err) return callback(err);
|
||||||
|
var distance = 0;
|
||||||
|
for (var i = 0; i < 64; i++) {
|
||||||
|
if (expectedFingerprint[i] !== actualFingerprint[i]) {
|
||||||
|
distance++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (distance > options.threshold) {
|
||||||
|
return callback(new Error('Expected maximum similarity distance: ' + options.threshold + '. Actual: ' + distance + '.'));
|
||||||
|
}
|
||||||
|
|
||||||
|
callback();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
},
|
||||||
|
|
||||||
|
assertMaxColourDistance: function(actualImagePath, expectedImagePath, acceptedDistance) {
|
||||||
|
if (typeof actualImagePath !== 'string') {
|
||||||
|
throw new TypeError('`actualImagePath` must be a string; got ' + actualImagePath);
|
||||||
|
}
|
||||||
|
if (typeof expectedImagePath !== 'string') {
|
||||||
|
throw new TypeError('`expectedImagePath` must be a string; got ' + expectedImagePath);
|
||||||
|
}
|
||||||
|
if (typeof acceptedDistance !== 'number') {
|
||||||
|
// Default threshold
|
||||||
|
acceptedDistance = 1;
|
||||||
|
}
|
||||||
|
var distance = maxColourDistance(actualImagePath, expectedImagePath);
|
||||||
|
if (distance > acceptedDistance) {
|
||||||
|
throw new Error('Expected maximum absolute distance of ' + acceptedDistance + ', actual ' + distance);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|||||||
BIN
test/fixtures/low-contrast.jpg
vendored
Normal file
|
After Width: | Height: | Size: 27 KiB |
@@ -3,6 +3,6 @@ if ! type valgrind >/dev/null; then
|
|||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
curl -O https://raw.githubusercontent.com/jcupitt/libvips/master/libvips.supp test/leak/libvips.supp
|
curl -O https://raw.githubusercontent.com/jcupitt/libvips/master/libvips.supp
|
||||||
cd ../../
|
cd ../../
|
||||||
G_SLICE=always-malloc G_DEBUG=gc-friendly valgrind --suppressions=test/leak/libvips.supp --suppressions=test/leak/sharp.supp --leak-check=full --show-leak-kinds=definite,indirect,possible --num-callers=20 --trace-children=yes npm test
|
G_SLICE=always-malloc G_DEBUG=gc-friendly valgrind --suppressions=test/leak/libvips.supp --suppressions=test/leak/sharp.supp --leak-check=full --show-leak-kinds=definite,indirect,possible --num-callers=20 --trace-children=yes npm test
|
||||||
|
|||||||
@@ -109,3 +109,35 @@
|
|||||||
...
|
...
|
||||||
fun:vips__init
|
fun:vips__init
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# *magick warnings
|
||||||
|
{
|
||||||
|
leak_magick_read
|
||||||
|
Memcheck:Leak
|
||||||
|
match-leak-kinds: definite,indirect,possible
|
||||||
|
...
|
||||||
|
fun:ReadImage
|
||||||
|
...
|
||||||
|
fun:vips__magick_read
|
||||||
|
}
|
||||||
|
{
|
||||||
|
leak_magick_read_header
|
||||||
|
Memcheck:Leak
|
||||||
|
match-leak-kinds: definite,indirect,possible
|
||||||
|
...
|
||||||
|
fun:ReadImage
|
||||||
|
...
|
||||||
|
fun:vips__magick_read_header
|
||||||
|
}
|
||||||
|
|
||||||
|
# glib g_file_read_link
|
||||||
|
# https://github.com/GNOME/glib/commit/49a5d0f6f2aed99cd78f25655f137f4448e47d92
|
||||||
|
{
|
||||||
|
leak_magick
|
||||||
|
Memcheck:Leak
|
||||||
|
match-leak-kinds: definite,indirect,possible
|
||||||
|
...
|
||||||
|
fun:g_file_read_link
|
||||||
|
...
|
||||||
|
fun:vips_gsf_path
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
var assert = require('assert');
|
var assert = require('assert');
|
||||||
|
|
||||||
var sharp = require('../../index');
|
|
||||||
var fixtures = require('../fixtures');
|
var fixtures = require('../fixtures');
|
||||||
|
var sharp = require('../../index');
|
||||||
|
|
||||||
sharp.cache(0);
|
sharp.cache(0);
|
||||||
|
|
||||||
@@ -13,7 +12,12 @@ describe('Alpha transparency', function() {
|
|||||||
sharp(fixtures.inputPngWithTransparency)
|
sharp(fixtures.inputPngWithTransparency)
|
||||||
.flatten()
|
.flatten()
|
||||||
.resize(400, 300)
|
.resize(400, 300)
|
||||||
.toFile(fixtures.path('output.flatten-black.jpg'), done);
|
.toBuffer(function(err, data, info) {
|
||||||
|
if (err) throw err;
|
||||||
|
assert.strictEqual(400, info.width);
|
||||||
|
assert.strictEqual(300, info.height);
|
||||||
|
fixtures.assertSimilar(fixtures.expected('flatten-black.jpg'), data, done);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('Flatten to RGB orange', function(done) {
|
it('Flatten to RGB orange', function(done) {
|
||||||
@@ -21,7 +25,12 @@ describe('Alpha transparency', function() {
|
|||||||
.flatten()
|
.flatten()
|
||||||
.background({r: 255, g: 102, b: 0})
|
.background({r: 255, g: 102, b: 0})
|
||||||
.resize(400, 300)
|
.resize(400, 300)
|
||||||
.toFile(fixtures.path('output.flatten-rgb-orange.jpg'), done);
|
.toBuffer(function(err, data, info) {
|
||||||
|
if (err) throw err;
|
||||||
|
assert.strictEqual(400, info.width);
|
||||||
|
assert.strictEqual(300, info.height);
|
||||||
|
fixtures.assertSimilar(fixtures.expected('flatten-orange.jpg'), data, done);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('Flatten to CSS/hex orange', function(done) {
|
it('Flatten to CSS/hex orange', function(done) {
|
||||||
@@ -29,7 +38,12 @@ describe('Alpha transparency', function() {
|
|||||||
.flatten()
|
.flatten()
|
||||||
.background('#ff6600')
|
.background('#ff6600')
|
||||||
.resize(400, 300)
|
.resize(400, 300)
|
||||||
.toFile(fixtures.path('output.flatten-hex-orange.jpg'), done);
|
.toBuffer(function(err, data, info) {
|
||||||
|
if (err) throw err;
|
||||||
|
assert.strictEqual(400, info.width);
|
||||||
|
assert.strictEqual(300, info.height);
|
||||||
|
fixtures.assertSimilar(fixtures.expected('flatten-orange.jpg'), data, done);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('Do not flatten', function(done) {
|
it('Do not flatten', function(done) {
|
||||||
@@ -61,4 +75,38 @@ describe('Alpha transparency', function() {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('Enlargement with non-nearest neighbor interpolation shouldn’t cause dark edges', function(done) {
|
||||||
|
var BASE_NAME = 'alpha-premultiply-enlargement-2048x1536-paper.png';
|
||||||
|
var actual = fixtures.path('output.' + BASE_NAME);
|
||||||
|
var expected = fixtures.expected(BASE_NAME);
|
||||||
|
sharp(fixtures.inputPngAlphaPremultiplicationSmall)
|
||||||
|
.resize(2048, 1536)
|
||||||
|
.interpolateWith('bicubic')
|
||||||
|
.toFile(actual, function(err) {
|
||||||
|
if (err) {
|
||||||
|
done(err);
|
||||||
|
} else {
|
||||||
|
fixtures.assertMaxColourDistance(actual, expected, 102);
|
||||||
|
done();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('Reduction with non-nearest neighbor interpolation shouldn’t cause dark edges', function(done) {
|
||||||
|
var BASE_NAME = 'alpha-premultiply-reduction-1024x768-paper.png';
|
||||||
|
var actual = fixtures.path('output.' + BASE_NAME);
|
||||||
|
var expected = fixtures.expected(BASE_NAME);
|
||||||
|
sharp(fixtures.inputPngAlphaPremultiplicationLarge)
|
||||||
|
.resize(1024, 768)
|
||||||
|
.interpolateWith('bicubic')
|
||||||
|
.toFile(actual, function(err) {
|
||||||
|
if (err) {
|
||||||
|
done(err);
|
||||||
|
} else {
|
||||||
|
fixtures.assertMaxColourDistance(actual, expected, 102);
|
||||||
|
done();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|||||||
58
test/unit/clone.js
Executable file
@@ -0,0 +1,58 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
var fs = require('fs');
|
||||||
|
var assert = require('assert');
|
||||||
|
|
||||||
|
var sharp = require('../../index');
|
||||||
|
var fixtures = require('../fixtures');
|
||||||
|
|
||||||
|
sharp.cache(0);
|
||||||
|
|
||||||
|
describe('Clone', function() {
|
||||||
|
it('Read from Stream and write to multiple Streams', function(done) {
|
||||||
|
var finishEventsExpected = 2;
|
||||||
|
// Output stream 1
|
||||||
|
var output1 = fixtures.path('output.multi-stream.1.jpg');
|
||||||
|
var writable1 = fs.createWriteStream(output1);
|
||||||
|
writable1.on('finish', function() {
|
||||||
|
sharp(output1).toBuffer(function(err, data, info) {
|
||||||
|
if (err) throw err;
|
||||||
|
assert.strictEqual(true, data.length > 0);
|
||||||
|
assert.strictEqual(data.length, info.size);
|
||||||
|
assert.strictEqual('jpeg', info.format);
|
||||||
|
assert.strictEqual(320, info.width);
|
||||||
|
assert.strictEqual(240, info.height);
|
||||||
|
fs.unlinkSync(output1);
|
||||||
|
finishEventsExpected--;
|
||||||
|
if (finishEventsExpected === 0) {
|
||||||
|
done();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
// Output stream 2
|
||||||
|
var output2 = fixtures.path('output.multi-stream.2.jpg');
|
||||||
|
var writable2 = fs.createWriteStream(output2);
|
||||||
|
writable2.on('finish', function() {
|
||||||
|
sharp(output2).toBuffer(function(err, data, info) {
|
||||||
|
if (err) throw err;
|
||||||
|
assert.strictEqual(true, data.length > 0);
|
||||||
|
assert.strictEqual(data.length, info.size);
|
||||||
|
assert.strictEqual('jpeg', info.format);
|
||||||
|
assert.strictEqual(100, info.width);
|
||||||
|
assert.strictEqual(122, info.height);
|
||||||
|
fs.unlinkSync(output2);
|
||||||
|
finishEventsExpected--;
|
||||||
|
if (finishEventsExpected === 0) {
|
||||||
|
done();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
// Create parent instance
|
||||||
|
var rotator = sharp().rotate(90);
|
||||||
|
// Cloned instances with differing dimensions
|
||||||
|
rotator.clone().resize(320, 240).pipe(writable1);
|
||||||
|
rotator.clone().resize(100).pipe(writable2);
|
||||||
|
// Go
|
||||||
|
fs.createReadStream(fixtures.inputJpg).pipe(rotator);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -31,16 +31,18 @@ describe('Colour space conversion', function() {
|
|||||||
.toFile(fixtures.path('output.greyscale-not.jpg'), done);
|
.toFile(fixtures.path('output.greyscale-not.jpg'), done);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('From 1-bit TIFF to sRGB WebP [slow]', function(done) {
|
if (sharp.format.webp.output.buffer) {
|
||||||
sharp(fixtures.inputTiff)
|
it('From 1-bit TIFF to sRGB WebP [slow]', function(done) {
|
||||||
.webp()
|
sharp(fixtures.inputTiff)
|
||||||
.toBuffer(function(err, data, info) {
|
.webp()
|
||||||
if (err) throw err;
|
.toBuffer(function(err, data, info) {
|
||||||
assert.strictEqual(true, data.length > 0);
|
if (err) throw err;
|
||||||
assert.strictEqual('webp', info.format);
|
assert.strictEqual(true, data.length > 0);
|
||||||
done();
|
assert.strictEqual('webp', info.format);
|
||||||
});
|
done();
|
||||||
});
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
it('From CMYK to sRGB', function(done) {
|
it('From CMYK to sRGB', function(done) {
|
||||||
sharp(fixtures.inputJpgWithCmykProfile)
|
sharp(fixtures.inputJpgWithCmykProfile)
|
||||||
|
|||||||
49
test/unit/cpplint.js
Executable file
@@ -0,0 +1,49 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
var fs = require('fs');
|
||||||
|
var path = require('path');
|
||||||
|
var assert = require('assert');
|
||||||
|
|
||||||
|
var cpplint = require('node-cpplint/lib/');
|
||||||
|
|
||||||
|
describe('cpplint', function() {
|
||||||
|
|
||||||
|
// Ignore cpplint failures, possibly newline-related, on Windows
|
||||||
|
if (process.platform !== 'win32') {
|
||||||
|
// List C++ source files
|
||||||
|
fs.readdirSync(path.join(__dirname, '..', '..', 'src')).forEach(function (source) {
|
||||||
|
var file = path.join('src', source);
|
||||||
|
it(file, function(done) {
|
||||||
|
// Lint each source file
|
||||||
|
cpplint({
|
||||||
|
files: [file],
|
||||||
|
linelength: 140,
|
||||||
|
filters: {
|
||||||
|
legal: {
|
||||||
|
copyright: false
|
||||||
|
},
|
||||||
|
build: {
|
||||||
|
include: false,
|
||||||
|
include_order: false
|
||||||
|
},
|
||||||
|
whitespace: {
|
||||||
|
blank_line: false,
|
||||||
|
comments: false,
|
||||||
|
parens: false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, function(err, report) {
|
||||||
|
if (err) {
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
var expected = {};
|
||||||
|
expected[file] = [];
|
||||||
|
assert.deepEqual(expected, report);
|
||||||
|
done();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
});
|
||||||
@@ -13,11 +13,11 @@ describe('Crop gravities', function() {
|
|||||||
sharp(fixtures.inputJpg)
|
sharp(fixtures.inputJpg)
|
||||||
.resize(320, 80)
|
.resize(320, 80)
|
||||||
.crop(sharp.gravity.north)
|
.crop(sharp.gravity.north)
|
||||||
.toFile(fixtures.path('output.gravity-north.jpg'), function(err, info) {
|
.toBuffer(function(err, data, info) {
|
||||||
if (err) throw err;
|
if (err) throw err;
|
||||||
assert.strictEqual(320, info.width);
|
assert.strictEqual(320, info.width);
|
||||||
assert.strictEqual(80, info.height);
|
assert.strictEqual(80, info.height);
|
||||||
done();
|
fixtures.assertSimilar(fixtures.expected('gravity-north.jpg'), data, done);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -25,11 +25,11 @@ describe('Crop gravities', function() {
|
|||||||
sharp(fixtures.inputJpg)
|
sharp(fixtures.inputJpg)
|
||||||
.resize(80, 320)
|
.resize(80, 320)
|
||||||
.crop(sharp.gravity.east)
|
.crop(sharp.gravity.east)
|
||||||
.toFile(fixtures.path('output.gravity-east.jpg'), function(err, info) {
|
.toBuffer(function(err, data, info) {
|
||||||
if (err) throw err;
|
if (err) throw err;
|
||||||
assert.strictEqual(80, info.width);
|
assert.strictEqual(80, info.width);
|
||||||
assert.strictEqual(320, info.height);
|
assert.strictEqual(320, info.height);
|
||||||
done();
|
fixtures.assertSimilar(fixtures.expected('gravity-east.jpg'), data, done);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -37,11 +37,11 @@ describe('Crop gravities', function() {
|
|||||||
sharp(fixtures.inputJpg)
|
sharp(fixtures.inputJpg)
|
||||||
.resize(320, 80)
|
.resize(320, 80)
|
||||||
.crop(sharp.gravity.south)
|
.crop(sharp.gravity.south)
|
||||||
.toFile(fixtures.path('output.gravity-south.jpg'), function(err, info) {
|
.toBuffer(function(err, data, info) {
|
||||||
if (err) throw err;
|
if (err) throw err;
|
||||||
assert.strictEqual(320, info.width);
|
assert.strictEqual(320, info.width);
|
||||||
assert.strictEqual(80, info.height);
|
assert.strictEqual(80, info.height);
|
||||||
done();
|
fixtures.assertSimilar(fixtures.expected('gravity-south.jpg'), data, done);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -49,11 +49,11 @@ describe('Crop gravities', function() {
|
|||||||
sharp(fixtures.inputJpg)
|
sharp(fixtures.inputJpg)
|
||||||
.resize(80, 320)
|
.resize(80, 320)
|
||||||
.crop(sharp.gravity.west)
|
.crop(sharp.gravity.west)
|
||||||
.toFile(fixtures.path('output.gravity-west.jpg'), function(err, info) {
|
.toBuffer(function(err, data, info) {
|
||||||
if (err) throw err;
|
if (err) throw err;
|
||||||
assert.strictEqual(80, info.width);
|
assert.strictEqual(80, info.width);
|
||||||
assert.strictEqual(320, info.height);
|
assert.strictEqual(320, info.height);
|
||||||
done();
|
fixtures.assertSimilar(fixtures.expected('gravity-west.jpg'), data, done);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -61,11 +61,11 @@ describe('Crop gravities', function() {
|
|||||||
sharp(fixtures.inputJpg)
|
sharp(fixtures.inputJpg)
|
||||||
.resize(320, 80)
|
.resize(320, 80)
|
||||||
.crop(sharp.gravity.center)
|
.crop(sharp.gravity.center)
|
||||||
.toFile(fixtures.path('output.gravity-center.jpg'), function(err, info) {
|
.toBuffer(function(err, data, info) {
|
||||||
if (err) throw err;
|
if (err) throw err;
|
||||||
assert.strictEqual(320, info.width);
|
assert.strictEqual(320, info.width);
|
||||||
assert.strictEqual(80, info.height);
|
assert.strictEqual(80, info.height);
|
||||||
done();
|
fixtures.assertSimilar(fixtures.expected('gravity-center.jpg'), data, done);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -73,23 +73,18 @@ describe('Crop gravities', function() {
|
|||||||
sharp(fixtures.inputJpg)
|
sharp(fixtures.inputJpg)
|
||||||
.resize(80, 320)
|
.resize(80, 320)
|
||||||
.crop(sharp.gravity.centre)
|
.crop(sharp.gravity.centre)
|
||||||
.toFile(fixtures.path('output.gravity-centre.jpg'), function(err, info) {
|
.toBuffer(function(err, data, info) {
|
||||||
if (err) throw err;
|
if (err) throw err;
|
||||||
assert.strictEqual(80, info.width);
|
assert.strictEqual(80, info.width);
|
||||||
assert.strictEqual(320, info.height);
|
assert.strictEqual(320, info.height);
|
||||||
done();
|
fixtures.assertSimilar(fixtures.expected('gravity-centre.jpg'), data, done);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('Invalid', function(done) {
|
it('Invalid', function() {
|
||||||
var isValid = true;
|
assert.throws(function() {
|
||||||
try {
|
|
||||||
sharp(fixtures.inputJpg).crop(5);
|
sharp(fixtures.inputJpg).crop(5);
|
||||||
} catch (err) {
|
});
|
||||||
isValid = false;
|
|
||||||
}
|
|
||||||
assert.strictEqual(false, isValid);
|
|
||||||
done();
|
|
||||||
});
|
});
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -28,18 +28,38 @@ describe('Embed', function() {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('JPEG within WebP, to include alpha channel', function(done) {
|
if (sharp.format.webp.output.buffer) {
|
||||||
sharp(fixtures.inputJpg)
|
it('JPEG within WebP, to include alpha channel', function(done) {
|
||||||
.resize(320, 240)
|
sharp(fixtures.inputJpg)
|
||||||
.background({r: 0, g: 0, b: 0, a: 0})
|
.resize(320, 240)
|
||||||
|
.background({r: 0, g: 0, b: 0, a: 0})
|
||||||
|
.embed()
|
||||||
|
.webp()
|
||||||
|
.toBuffer(function(err, data, info) {
|
||||||
|
if (err) throw err;
|
||||||
|
assert.strictEqual(true, data.length > 0);
|
||||||
|
assert.strictEqual('webp', info.format);
|
||||||
|
assert.strictEqual(320, info.width);
|
||||||
|
assert.strictEqual(240, info.height);
|
||||||
|
sharp(data).metadata(function(err, metadata) {
|
||||||
|
if (err) throw err;
|
||||||
|
assert.strictEqual(4, metadata.channels);
|
||||||
|
done();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
it('PNG with alpha channel', function(done) {
|
||||||
|
sharp(fixtures.inputPngWithTransparency)
|
||||||
|
.resize(50, 50)
|
||||||
.embed()
|
.embed()
|
||||||
.webp()
|
|
||||||
.toBuffer(function(err, data, info) {
|
.toBuffer(function(err, data, info) {
|
||||||
if (err) throw err;
|
if (err) throw err;
|
||||||
assert.strictEqual(true, data.length > 0);
|
assert.strictEqual(true, data.length > 0);
|
||||||
assert.strictEqual('webp', info.format);
|
assert.strictEqual('png', info.format);
|
||||||
assert.strictEqual(320, info.width);
|
assert.strictEqual(50, info.width);
|
||||||
assert.strictEqual(240, info.height);
|
assert.strictEqual(50, info.height);
|
||||||
sharp(data).metadata(function(err, metadata) {
|
sharp(data).metadata(function(err, metadata) {
|
||||||
if (err) throw err;
|
if (err) throw err;
|
||||||
assert.strictEqual(4, metadata.channels);
|
assert.strictEqual(4, metadata.channels);
|
||||||
@@ -48,4 +68,18 @@ describe('Embed', function() {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('Enlarge and embed', function(done) {
|
||||||
|
sharp(fixtures.inputPngWithOneColor)
|
||||||
|
.embed()
|
||||||
|
.resize(320, 240)
|
||||||
|
.toBuffer(function(err, data, info) {
|
||||||
|
if (err) throw err;
|
||||||
|
assert.strictEqual(true, data.length > 0);
|
||||||
|
assert.strictEqual('png', info.format);
|
||||||
|
assert.strictEqual(320, info.width);
|
||||||
|
assert.strictEqual(240, info.height);
|
||||||
|
fixtures.assertSimilar(fixtures.expected('embed-enlarge.png'), data, done);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -12,44 +12,47 @@ describe('Partial image extraction', function() {
|
|||||||
it('JPEG', function(done) {
|
it('JPEG', function(done) {
|
||||||
sharp(fixtures.inputJpg)
|
sharp(fixtures.inputJpg)
|
||||||
.extract(2, 2, 20, 20)
|
.extract(2, 2, 20, 20)
|
||||||
.toFile(fixtures.path('output.extract.jpg'), function(err, info) {
|
.toBuffer(function(err, data, info) {
|
||||||
if (err) throw err;
|
if (err) throw err;
|
||||||
assert.strictEqual(20, info.width);
|
assert.strictEqual(20, info.width);
|
||||||
assert.strictEqual(20, info.height);
|
assert.strictEqual(20, info.height);
|
||||||
done();
|
fixtures.assertSimilar(fixtures.expected('extract.jpg'), data, done);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('PNG', function(done) {
|
it('PNG', function(done) {
|
||||||
sharp(fixtures.inputPng)
|
sharp(fixtures.inputPng)
|
||||||
.extract(300, 200, 400, 200)
|
.extract(300, 200, 400, 200)
|
||||||
.toFile(fixtures.path('output.extract.png'), function(err, info) {
|
.toBuffer(function(err, data, info) {
|
||||||
if (err) throw err;
|
if (err) throw err;
|
||||||
assert.strictEqual(400, info.width);
|
assert.strictEqual(400, info.width);
|
||||||
assert.strictEqual(200, info.height);
|
assert.strictEqual(200, info.height);
|
||||||
done();
|
fixtures.assertSimilar(fixtures.expected('extract.png'), data, done);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('WebP', function(done) {
|
if (sharp.format.webp.output.file) {
|
||||||
sharp(fixtures.inputWebP)
|
it('WebP', function(done) {
|
||||||
.extract(50, 100, 125, 200)
|
sharp(fixtures.inputWebP)
|
||||||
.toFile(fixtures.path('output.extract.webp'), function(err, info) {
|
.extract(50, 100, 125, 200)
|
||||||
if (err) throw err;
|
.toBuffer(function(err, data, info) {
|
||||||
assert.strictEqual(125, info.width);
|
if (err) throw err;
|
||||||
assert.strictEqual(200, info.height);
|
assert.strictEqual(125, info.width);
|
||||||
done();
|
assert.strictEqual(200, info.height);
|
||||||
});
|
fixtures.assertSimilar(fixtures.expected('extract.webp'), data, done);
|
||||||
});
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
it('TIFF', function(done) {
|
it('TIFF', function(done) {
|
||||||
sharp(fixtures.inputTiff)
|
sharp(fixtures.inputTiff)
|
||||||
.extract(63, 34, 341, 529)
|
.extract(63, 34, 341, 529)
|
||||||
.toFile(fixtures.path('output.extract.tiff'), function(err, info) {
|
.jpeg()
|
||||||
|
.toBuffer(function(err, data, info) {
|
||||||
if (err) throw err;
|
if (err) throw err;
|
||||||
assert.strictEqual(341, info.width);
|
assert.strictEqual(341, info.width);
|
||||||
assert.strictEqual(529, info.height);
|
assert.strictEqual(529, info.height);
|
||||||
done();
|
fixtures.assertSimilar(fixtures.expected('extract.tiff'), data, done);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -57,11 +60,11 @@ describe('Partial image extraction', function() {
|
|||||||
sharp(fixtures.inputJpg)
|
sharp(fixtures.inputJpg)
|
||||||
.extract(10, 10, 10, 500, 500)
|
.extract(10, 10, 10, 500, 500)
|
||||||
.resize(100, 100)
|
.resize(100, 100)
|
||||||
.toFile(fixtures.path('output.extract.resize.jpg'), function(err, info) {
|
.toBuffer(function(err, data, info) {
|
||||||
if (err) throw err;
|
if (err) throw err;
|
||||||
assert.strictEqual(100, info.width);
|
assert.strictEqual(100, info.width);
|
||||||
assert.strictEqual(100, info.height);
|
assert.strictEqual(100, info.height);
|
||||||
done();
|
fixtures.assertSimilar(fixtures.expected('extract-resize.jpg'), data, done);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -70,11 +73,11 @@ describe('Partial image extraction', function() {
|
|||||||
.resize(500, 500)
|
.resize(500, 500)
|
||||||
.crop(sharp.gravity.north)
|
.crop(sharp.gravity.north)
|
||||||
.extract(10, 10, 100, 100)
|
.extract(10, 10, 100, 100)
|
||||||
.toFile(fixtures.path('output.resize.crop.extract.jpg'), function(err, info) {
|
.toBuffer(function(err, data, info) {
|
||||||
if (err) throw err;
|
if (err) throw err;
|
||||||
assert.strictEqual(100, info.width);
|
assert.strictEqual(100, info.width);
|
||||||
assert.strictEqual(100, info.height);
|
assert.strictEqual(100, info.height);
|
||||||
done();
|
fixtures.assertSimilar(fixtures.expected('resize-crop-extract.jpg'), data, done);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -84,12 +87,69 @@ describe('Partial image extraction', function() {
|
|||||||
.resize(500, 500)
|
.resize(500, 500)
|
||||||
.crop(sharp.gravity.north)
|
.crop(sharp.gravity.north)
|
||||||
.extract(10, 10, 100, 100)
|
.extract(10, 10, 100, 100)
|
||||||
.toFile(fixtures.path('output.extract.resize.crop.extract.jpg'), function(err, info) {
|
.toBuffer(function(err, data, info) {
|
||||||
if (err) throw err;
|
if (err) throw err;
|
||||||
assert.strictEqual(100, info.width);
|
assert.strictEqual(100, info.width);
|
||||||
assert.strictEqual(100, info.height);
|
assert.strictEqual(100, info.height);
|
||||||
done();
|
fixtures.assertSimilar(fixtures.expected('extract-resize-crop-extract.jpg'), data, done);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('Extract then rotate', function(done) {
|
||||||
|
sharp(fixtures.inputJpg)
|
||||||
|
.extract(10, 10, 100, 100)
|
||||||
|
.rotate(90)
|
||||||
|
.toBuffer(function(err, data, info) {
|
||||||
|
if (err) throw err;
|
||||||
|
assert.strictEqual(100, info.width);
|
||||||
|
assert.strictEqual(100, info.height);
|
||||||
|
fixtures.assertSimilar(fixtures.expected('extract-rotate.jpg'), data, done);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('Rotate then extract', function(done) {
|
||||||
|
sharp(fixtures.inputJpg)
|
||||||
|
.rotate(90)
|
||||||
|
.extract(10, 10, 100, 100)
|
||||||
|
.toBuffer(function(err, data, info) {
|
||||||
|
if (err) throw err;
|
||||||
|
assert.strictEqual(100, info.width);
|
||||||
|
assert.strictEqual(100, info.height);
|
||||||
|
fixtures.assertSimilar(fixtures.expected('rotate-extract.jpg'), data, done);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Invalid parameters', function() {
|
||||||
|
|
||||||
|
it('Undefined', function() {
|
||||||
|
assert.throws(function() {
|
||||||
|
sharp(fixtures.inputJpg).extract();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('String top', function() {
|
||||||
|
assert.throws(function() {
|
||||||
|
sharp(fixtures.inputJpg).extract('spoons', 10, 10, 10);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('Non-integral left', function() {
|
||||||
|
assert.throws(function() {
|
||||||
|
sharp(fixtures.inputJpg).extract(10, 10.2, 10, 10);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('Negative width - negative', function() {
|
||||||
|
assert.throws(function() {
|
||||||
|
sharp(fixtures.inputJpg).extract(10, 10, -10, 10);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('Null height', function() {
|
||||||
|
assert.throws(function() {
|
||||||
|
sharp(fixtures.inputJpg).extract(10, 10, 10, null);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
26
test/unit/fixtures.js
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
var assert = require('assert');
|
||||||
|
var fixtures = require('../fixtures');
|
||||||
|
|
||||||
|
describe('Test fixtures', function() {
|
||||||
|
describe('assertMaxColourDistance', function() {
|
||||||
|
it('should throw an Error when images have a different number of channels', function() {
|
||||||
|
assert.throws(function() {
|
||||||
|
fixtures.assertMaxColourDistance(fixtures.inputPngOverlayLayer1, fixtures.inputJpg);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
it('should throw an Error when images have different dimensions', function() {
|
||||||
|
assert.throws(function() {
|
||||||
|
fixtures.assertMaxColourDistance(fixtures.inputJpg, fixtures.inputJpgWithExif);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
it('should accept a zero threshold when comparing an image to itself', function() {
|
||||||
|
var image = fixtures.inputPngOverlayLayer0;
|
||||||
|
fixtures.assertMaxColourDistance(image, image, 0);
|
||||||
|
});
|
||||||
|
it('should accept a numeric threshold for two different images', function() {
|
||||||
|
fixtures.assertMaxColourDistance(fixtures.inputPngOverlayLayer0, fixtures.inputPngOverlayLayer1, 100);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||