'Get Dominant Color from Image in UWP C#

Basically I have a UWP app that allows user to open image files (.jpg, .jpeg, .png) and I need to detect the dominant color from that image.

I found solutions with GDI+ using System.Drawing but That's not available in UWP. I couldn't find any reference of similar thing in Win2D. So is there a way to get the dominant color from Histogram?

I can always use any Web Service and get this done with python or node.js etc but I want to do it natively inside the UWP app without the requirement of internet.

Any Help Appreciated !



Solution 1:[1]

We did it in the following way:

For each pixel: Convert to HSL. Use H and S to determine the color. Use L to determine the intensity. Sum all up a in a 2D matrix indexed by H and S.

Find the largest value in the matrix. That is your dominant color.

Solution 2:[2]

Take a look at this repo: ColorThief and its Nuget package. It has support for UWP. You can also check this answer for more info.

Solution 3:[3]

UWP Works revise the code above

//ksemenenko.ColorThief Nuget
async Task<SolidColorBrush> GetIdealTextColor(StorageFile file)
        {
            var solid = new SolidColorBrush();
            solid = TextBlockHelper._textBrush;
            var random = RandomAccessStreamReference.CreateFromFile(file); 
            using (IRandomAccessStream randomAccessStream = await random.OpenReadAsync())
            { 
                var decoder = await BitmapDecoder.CreateAsync(randomAccessStream); 
                var colorThief = new ColorThiefDotNet.ColorThief();
                var quantizedColor = await colorThief.GetColor(decoder);
               
                solid = IdealTextColor(quantizedColor.Color);
            }
            return solid;
        }

public SolidColorBrush IdealTextColor(ColorThiefDotNet.Color bg)
        {
            int nThreshold = 105;
            int bgDelta = Convert.ToInt32((bg.R * 0.299) + (bg.G * 0.587) +
                                          (bg.B * 0.114));

            var foreColor = (255 - bgDelta < nThreshold) ? new SolidColorBrush(Colors.Black) : new SolidColorBrush(Colors.White);
            return foreColor;
        }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 PepitoSh
Solution 2
Solution 3 user18763174