Skip to content

Commit

Permalink
perf(gatsby-plugin-image): downsize image before extracting dominant …
Browse files Browse the repository at this point in the history
…color (#35814)

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

* chore: use larger image size
  • Loading branch information
ascorbic committed Jun 2, 2022
1 parent b0db9a0 commit 5e6c808
Showing 1 changed file with 12 additions and 1 deletion.
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

0 comments on commit 5e6c808

Please sign in to comment.