Skip to content
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

perf(gatsby-plugin-image): downsize image before extracting dominant color #35814

Merged
merged 2 commits into from
Jun 2, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion packages/gatsby-plugin-sharp/src/image-data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ import { reportError } from "./report-error"

const DEFAULT_BLURRED_IMAGE_WIDTH = 20

const DOMINANT_COLOR_IMAGE_SIZE = 200

const DEFAULT_BREAKPOINTS = [750, 1080, 1366, 1920]

type ImageFormat = "jpg" | "png" | "webp" | "avif" | "" | "auto"
Expand Down Expand Up @@ -66,7 +68,16 @@ export async function getImageMetadata(

const { width, height, density, format } = await pipeline.metadata()

const { dominant } = await pipeline.stats()
// Downsize the image before calculating the dominant color
const buffer = await pipeline
.resize(DOMINANT_COLOR_IMAGE_SIZE, DOMINANT_COLOR_IMAGE_SIZE, {
fit: `inside`,
withoutEnlargement: true,
})
.toBuffer()

const { dominant } = await sharp(buffer).stats()

// Fallback in case sharp doesn't support dominant
const dominantColor = dominant
? rgbToHex(dominant.r, dominant.g, dominant.b)
Expand Down