|
1 | 1 | const sharp = require('sharp')
|
2 | 2 | const path = require('path')
|
| 3 | +const fs = require('fs') |
3 | 4 |
|
4 | 5 | exports.handler = async event => {
|
5 | 6 | try {
|
| 7 | + // Read the file to a buffer |
6 | 8 | const imagePath = path.resolve('./src/lucky.jpg')
|
7 |
| - console.log(imagePath) |
8 |
| - const img = await sharp(imagePath) |
9 |
| - .withMetadata() |
10 |
| - .resize(800) |
11 |
| - .convolve({ |
| 9 | + const imgBuf = fs.readFileSync(imagePath) |
| 10 | + |
| 11 | + // Extract the qs from the event |
| 12 | + const { queryStringParameters } = event |
| 13 | + console.log(`Got query params `, queryStringParameters) |
| 14 | + const { width, height, metadata, convolve } = queryStringParameters |
| 15 | + |
| 16 | + // Let's create the sharp instance |
| 17 | + const img = sharp(imgBuf) |
| 18 | + |
| 19 | + if (metadata === 'true') { |
| 20 | + img.withMetadata() |
| 21 | + } |
| 22 | + |
| 23 | + img.resize({ |
| 24 | + width: parseInt(width, 10) || 800, |
| 25 | + height: parseInt(height, 10), |
| 26 | + fit: sharp.fit.cover, |
| 27 | + position: sharp.strategy.entropy |
| 28 | + }) |
| 29 | + |
| 30 | + // for fun of it 😎 |
| 31 | + if (convolve === 'true') { |
| 32 | + img.convolve({ |
12 | 33 | width: 3,
|
13 | 34 | height: 3,
|
14 | 35 | kernel: [-1, 0, 1, -2, 0, 2, -1, 0, 1]
|
15 | 36 | })
|
16 |
| - .webp() |
17 |
| - .toBuffer() |
| 37 | + } |
| 38 | + |
| 39 | + // transform to the webp format |
| 40 | + img.webp() |
| 41 | + |
| 42 | + // last thing is to get the buffer of cloned instance |
| 43 | + const image = await img.clone().toBuffer() |
18 | 44 |
|
19 | 45 | const response = {
|
20 | 46 | statusCode: 200,
|
21 | 47 | headers: {
|
22 | 48 | 'Content-Type': 'image/webp'
|
23 | 49 | },
|
24 |
| - body: img.toString('base64'), |
| 50 | + body: image.toString('base64'), |
25 | 51 | isBase64Encoded: true
|
26 | 52 | }
|
27 | 53 | return response
|
|
0 commit comments