|
1 |
| -const jimp = require('jimp') |
| 1 | +const path = require('path') |
| 2 | +const { builder } = require('@netlify/functions') |
| 3 | +const sharp = require('sharp') |
| 4 | +const fetch = require('node-fetch') |
2 | 5 |
|
3 | 6 | // Function used to mimic next/image and sharp
|
4 |
| -exports.handler = async (event) => { |
5 |
| - const { url, w = 500, q = 75 } = event.queryStringParameters |
| 7 | +const handler = async (event) => { |
| 8 | + const [,, url, w = 500, q = 75] = event.path.split('/') |
| 9 | + const parsedUrl = decodeURIComponent(url) |
6 | 10 | const width = parseInt(w)
|
7 | 11 | const quality = parseInt(q)
|
8 | 12 |
|
9 |
| - const imageUrl = url.startsWith('/') ? `${process.env.DEPLOY_URL || `http://${event.headers.host}`}${url}` : url |
10 |
| - const image = await jimp.read(imageUrl) |
11 |
| - |
12 |
| - image.resize(width, jimp.AUTO).quality(quality) |
| 13 | + const imageUrl = parsedUrl.startsWith('/') ? `${process.env.DEPLOY_URL || `http://${event.headers.host}`}${parsedUrl}` : parsedUrl |
| 14 | + const imageData = await fetch(imageUrl) |
| 15 | + const bufferData = await imageData.buffer() |
| 16 | + const ext = path.extname(imageUrl) |
| 17 | + const mimeType = ext === 'jpg' ? `image/jpeg` : `image/${ext}` |
| 18 | + let image = await sharp(bufferData) |
| 19 | + if (mimeType === 'image/webp') { |
| 20 | + image = image.webp({ quality }) |
| 21 | + } else if (mimeType === 'image/jpeg') { |
| 22 | + image = image.jpeg({ quality }) |
| 23 | + } else if (mimeType === 'image/png') { |
| 24 | + image = image.png({ quality }) |
| 25 | + } else if (mimeType === 'image/avif') { |
| 26 | + image = image.avif({ quality }) |
| 27 | + } else if (mimeType === 'image/tiff') { |
| 28 | + image = image.tiff({ quality }) |
| 29 | + } else if (mimeType === 'image/heif') { |
| 30 | + image = image.heif({ quality }) |
| 31 | + } |
13 | 32 |
|
14 |
| - const imageBuffer = await image.getBufferAsync(image.getMIME()) |
| 33 | + const imageBuffer = await image.resize(width).toBuffer() |
15 | 34 |
|
16 | 35 | return {
|
17 | 36 | statusCode: 200,
|
18 | 37 | headers: {
|
19 |
| - 'Content-Type': image.getMIME(), |
| 38 | + 'Content-Type': mimeType, |
20 | 39 | },
|
21 | 40 | body: imageBuffer.toString('base64'),
|
22 | 41 | isBase64Encoded: true,
|
23 | 42 | }
|
24 | 43 | }
|
| 44 | + |
| 45 | +exports.handler = builder(handler) |
0 commit comments