Skip to content

Commit 5b6aee6

Browse files
committedSep 16, 2019
update the example
1 parent 0eb81a1 commit 5b6aee6

File tree

2 files changed

+38
-8
lines changed

2 files changed

+38
-8
lines changed
 

‎README.md

+4
Original file line numberDiff line numberDiff line change
@@ -5,3 +5,7 @@ Sharp js as a layer,
55
## Image copyright
66

77
`lucky.jpg` is owned by me
8+
9+
## Example
10+
11+
http://0.0.0.0:4000/sharp?width=800&metadata=true&convolve=true

‎example/src/handler.js

+34-8
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,53 @@
11
const sharp = require('sharp')
22
const path = require('path')
3+
const fs = require('fs')
34

45
exports.handler = async event => {
56
try {
7+
// Read the file to a buffer
68
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({
1233
width: 3,
1334
height: 3,
1435
kernel: [-1, 0, 1, -2, 0, 2, -1, 0, 1]
1536
})
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()
1844

1945
const response = {
2046
statusCode: 200,
2147
headers: {
2248
'Content-Type': 'image/webp'
2349
},
24-
body: img.toString('base64'),
50+
body: image.toString('base64'),
2551
isBase64Encoded: true
2652
}
2753
return response

0 commit comments

Comments
 (0)
Please sign in to comment.