Getting the average color of an image in Sanity CMS
Good news! Sanity actually does this automatically for you - no custom components or client-side processing needed.
When you upload an image to Sanity, the platform automatically extracts a color palette from the image and stores it as metadata. This includes dominant colors, average colors, background colors, and foreground colors. The palette metadata is generated server-side during the upload process, so you don't have to worry about the computational expense on the client side.
How to enable it
In your schema, configure the image field with the palette metadata option:
{
name: 'myImage',
type: 'image',
options: {
metadata: ['palette'] // Actually included by default!
}
}The palette metadata is actually included by default along with blurhash and lqip, so you might already have this data available without any configuration changes.
Accessing the palette data
Once configured, you can query the palette information like this:
*[_type == "myDocument"] {
myImage {
asset-> {
metadata {
palette {
dominant {
background,
foreground
},
darkMuted {
background,
foreground
},
lightVibrant {
background,
foreground
},
// ... other palette variations
}
}
}
}
}The palette object contains multiple color variations including dominant, muted, vibrant colors in both light and dark variants - giving you way more than just 2-3 colors to work with!
Important notes
- The metadata is processed asynchronously after upload, so there might be a brief delay before it's available
- The processing happens entirely on Sanity's servers during the asset pipeline
- You can use these colors for dynamic theming, like changing backgrounds or headers based on the dominant image colors
This is exactly the use case Sanity's image metadata was designed for - offloading expensive image processing to the CMS so your client applications can just consume the pre-computed data!
Sanity ā Build the way you think, not the way your CMS thinks
Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.