|
1 |
| -var path = require('path'); |
2 |
| -var assert = require('chai').assert; |
| 1 | +const fs = require('fs'); |
| 2 | +const path = require('path'); |
| 3 | +const assert = require('chai').assert; |
3 | 4 |
|
4 |
| -var smartcrop = require('../index.js'); |
| 5 | +const smartcrop = require('../index.js'); |
| 6 | +const https = require('https'); |
5 | 7 |
|
6 |
| -var imageSrc = path.resolve(__dirname, 'flower.jpg'); |
| 8 | +const imageSrc = path.resolve(__dirname, 'flower.jpg'); |
| 9 | +const imageSrcHttp = 'https://raw.githubusercontent.com/jwagner/smartcrop-gm/master/test/flower.jpg'; |
7 | 10 |
|
8 | 11 | describe('smartcrop', function() {
|
9 | 12 | describe('crop', function() {
|
| 13 | + function validateCrop(data) { |
| 14 | + assert(data.topCrop, 0); |
| 15 | + assert.equal(data.topCrop.x, 0); |
| 16 | + assert.equal(data.topCrop.y, 26); |
| 17 | + assert.equal(data.topCrop.width, 427); |
| 18 | + assert.equal(data.topCrop.height, 427); |
| 19 | + } |
10 | 20 | it('returns a valid crop', function() {
|
11 | 21 | return smartcrop
|
12 | 22 | .crop(imageSrc, { width: 128, height: 128, minScale: 1 })
|
13 |
| - .then(function(data) { |
14 |
| - assert(data.topCrop, 0); |
15 |
| - assert.equal(data.topCrop.x, 0); |
16 |
| - assert.equal(data.topCrop.y, 26); |
17 |
| - assert.equal(data.topCrop.width, 427); |
18 |
| - assert.equal(data.topCrop.height, 427); |
| 23 | + .then(validateCrop); |
| 24 | + }); |
| 25 | + it('accepts a stream', function() { |
| 26 | + function httpsGetBuffer(src) { |
| 27 | + return new Promise((resolve,reject) => { |
| 28 | + const chunks = []; |
| 29 | + https.get(src, (response) => { |
| 30 | + response.on('data', chunk => chunks.push(chunk)); |
| 31 | + response.on('end', () => resolve(Buffer.concat(chunks))); |
| 32 | + response.on('error', reject); |
| 33 | + }); |
| 34 | + }); |
| 35 | + } |
| 36 | + return httpsGetBuffer(imageSrcHttp).then(responseBodyBuffer => |
| 37 | + smartcrop |
| 38 | + .crop(responseBodyBuffer, { width: 128, height: 128, minScale: 1 }) |
| 39 | + ).then(validateCrop); |
| 40 | + }); |
| 41 | + }); |
| 42 | + describe('readme example', function() { |
| 43 | + it('writes a file', function() { |
| 44 | + var sharp = require('sharp'); |
| 45 | + |
| 46 | + function applySmartCrop(src, dest, width, height) { |
| 47 | + return smartcrop.crop(src, { width: width, height: height }).then(function(result) { |
| 48 | + var crop = result.topCrop; |
| 49 | + return sharp(src) |
| 50 | + .extract({ width: crop.width, height: crop.height, left: crop.x, top: crop.y }) |
| 51 | + .resize(width, height) |
| 52 | + .toFile(dest); |
| 53 | + }).then(() => { |
| 54 | + fs.unlinkSync(dest); |
19 | 55 | });
|
| 56 | + } |
| 57 | + |
| 58 | + return applySmartCrop(imageSrc, 'flower-square.jpg', 128, 128); |
20 | 59 | });
|
21 | 60 | });
|
22 | 61 | });
|
0 commit comments