-
Notifications
You must be signed in to change notification settings - Fork 86
fix: refactor image function #317
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+131
−33
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,52 +1,95 @@ | ||
const path = require('path') | ||
const { builder } = require('@netlify/functions') | ||
const sharp = require('sharp') | ||
const fetch = require('node-fetch') | ||
const imageType = require('image-type') | ||
const isSvg = require('is-svg') | ||
|
||
// Function used to mimic next/image and sharp | ||
function getImageType(buffer) { | ||
const type = imageType(buffer) | ||
if (type) { | ||
return type | ||
} | ||
if (isSvg(buffer)) { | ||
return { ext: 'svg', mime: 'image/svg' } | ||
} | ||
return null | ||
} | ||
|
||
const IGNORED_FORMATS = new Set(['svg', 'gif']) | ||
const OUTPUT_FORMATS = new Set(['png', 'jpg', 'webp', 'avif']) | ||
|
||
// Function used to mimic next/image | ||
const handler = async (event) => { | ||
const [, , url, w = 500, q = 75] = event.path.split('/') | ||
const parsedUrl = decodeURIComponent(url) | ||
// Work-around a bug in redirect handling. Remove when fixed. | ||
const parsedUrl = decodeURIComponent(url).replace('+', '%20') | ||
const width = parseInt(w) | ||
const quality = parseInt(q) | ||
|
||
if (!width) { | ||
return { | ||
statusCode: 400, | ||
body: 'Invalid image parameters', | ||
} | ||
} | ||
|
||
const quality = parseInt(q) || 60 | ||
|
||
const imageUrl = parsedUrl.startsWith('/') | ||
? `${process.env.DEPLOY_URL || `http://${event.headers.host}`}${parsedUrl}` | ||
: parsedUrl | ||
|
||
const imageData = await fetch(imageUrl) | ||
|
||
if (!imageData.ok) { | ||
console.error(`Failed to download image ${imageUrl}. Status ${imageData.status} ${imageData.statusText}`) | ||
return { | ||
statusCode: imageData.status, | ||
body: imageData.statusText, | ||
} | ||
} | ||
|
||
const bufferData = await imageData.buffer() | ||
const ext = path.extname(imageUrl) | ||
const mimeType = ext === 'jpg' ? `image/jpeg` : `image/${ext}` | ||
|
||
let image | ||
let imageBuffer | ||
|
||
if (mimeType === 'image/gif') { | ||
image = await sharp(bufferData, { animated: true }) | ||
// gif resizing in sharp seems unstable (https://github.com/lovell/sharp/issues/2275) | ||
imageBuffer = await image.toBuffer() | ||
} else { | ||
image = await sharp(bufferData) | ||
if (mimeType === 'image/webp') { | ||
image = image.webp({ quality }) | ||
} else if (mimeType === 'image/jpeg') { | ||
image = image.jpeg({ quality }) | ||
} else if (mimeType === 'image/png') { | ||
image = image.png({ quality }) | ||
} else if (mimeType === 'image/avif') { | ||
image = image.avif({ quality }) | ||
} else if (mimeType === 'image/tiff') { | ||
image = image.tiff({ quality }) | ||
} else if (mimeType === 'image/heif') { | ||
image = image.heif({ quality }) | ||
|
||
const type = getImageType(bufferData) | ||
|
||
if (!type) { | ||
return { statusCode: 400, body: 'Source does not appear to be an image' } | ||
} | ||
|
||
let { ext } = type | ||
|
||
// For unsupported formats (gif, svg) we redirect to the original | ||
if (IGNORED_FORMATS.has(ext)) { | ||
return { | ||
statusCode: 302, | ||
headers: { | ||
Location: imageUrl, | ||
}, | ||
} | ||
imageBuffer = await image.resize(width).toBuffer() | ||
} | ||
|
||
if (process.env.FORCE_WEBP_OUTPUT) { | ||
ext = 'webp' | ||
} | ||
|
||
if (!OUTPUT_FORMATS.has(ext)) { | ||
ext = 'jpg' | ||
} | ||
|
||
// The format methods are just to set options: they don't | ||
// make it return that format. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. oh huh ok!!!!! |
||
const { info, data: imageBuffer } = await sharp(bufferData) | ||
.jpeg({ quality, force: ext === 'jpg' }) | ||
.webp({ quality, force: ext === 'webp' }) | ||
.png({ quality, force: ext === 'png' }) | ||
.avif({ quality, force: ext === 'avif' }) | ||
.resize(width) | ||
.toBuffer({ resolveWithObject: true }) | ||
|
||
return { | ||
statusCode: 200, | ||
headers: { | ||
'Content-Type': mimeType, | ||
'Content-Type': `image/${info.format}`, | ||
}, | ||
body: imageBuffer.toString('base64'), | ||
isBase64Encoded: true, | ||
|
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🔥