Skip to content

Instantly share code, notes, and snippets.

@JimBobSquarePants
Created June 7, 2018 11:58
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JimBobSquarePants/12e0ef5d904d03110febea196cf1d6ee to your computer and use it in GitHub Desktop.
Save JimBobSquarePants/12e0ef5d904d03110febea196cf1d6ee to your computer and use it in GitHub Desktop.
Get dominant color from an image using ImageSharp and ImageProcessor
// ##### ImageSharp #####
using (var image = Image.Load<Rgb24>(inPath))
{
image.Mutate(
x => x
// Scale the image down preserving the aspect ratio. This will speed up quantization.
// We use nearest neighbor as it will be the fastest approach.
.Resize(new ResizeOptions() { Sampler = KnownResamplers.NearestNeighbor, Size = new Size(100, 0) })
// Reduce the color palette to 1 color without dithering.
.Quantize(new OctreeQuantizer(null, 1)));
Rgb24 dominant = image[0, 0];
}
// ##### ImageProcessor #####
using (var factory = new ImageFactory())
{
// Scale the image down preserving the aspect ratio.
// This will speed up quantization.
factory.Load(inPath).Resize(new Size(100, 0));
// Reduce the color palette to 1 color.
var octree = new OctreeQuantizer(1, 1);
using (Bitmap quantized = octree.Quantize(factory.Image))
{
// All pixels will share same color
Color dominent = quantized.GetPixel(0, 0);
}
}
@Webreaper
Copy link

Oooh, ya beauty. I'm trying to factor System.Drawing Bitmaps out of my app, and this is exactly what I need. Thanks!

@JimBobSquarePants
Copy link
Author

Glad it’s useful!

@lofcz
Copy link

lofcz commented Apr 1, 2024

This should be .Quantize(new OctreeQuantizer(new QuantizerOptions { MaxColors = 1 }))); for v3. Thanks Jim.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment