Created
June 7, 2018 11:58
-
-
Save JimBobSquarePants/12e0ef5d904d03110febea196cf1d6ee to your computer and use it in GitHub Desktop.
Get dominant color from an image using ImageSharp and ImageProcessor
This file contains 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
// ##### 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); | |
} | |
} |
Glad it’s useful!
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
Oooh, ya beauty. I'm trying to factor System.Drawing Bitmaps out of my app, and this is exactly what I need. Thanks!