Reputation: 578
In my UWP app we have images that users upload and they can be pretty much any size - so when I load these into in an Image control I resize them proportionally so they fit best into our image container (which is fixed at 112w x 152h) but as some images are wider than higher what I want to is find the background color of the image so I can set the Background of the image.
So to do this I am using the NuGet ColorThief package and the code below (taken from the sample I found there) is returning me the wrong dominant color in many cases:
var ct = new ColorThief();
QuantizedColor qc = await ct.GetColor(decoder); //BitmapDecoder containing image
Windows.UI.Color c = Windows.UI.Color.FromArgb(qc.Color.A, qc.Color.R, qc.Color.G, qc.Color.B);
setImageBackgroundColor(bgColour);
One image I tried it on was this one - now the dominant colour should clearly be black but it's returning some medium grey colour.... so is there something wrong with my code or my image or is there something else I need to do? I'm just not finding it reliable but I know others use it without issue.
Upvotes: 2
Views: 1717
Reputation: 3
In my opinion you need to set quality from 5 to 10 and use GetPalette method with first color from palette.
QuantizedColor dominantColor = colorThief.GetPalette(tempBitmap, 5, 5, true)[0];
Upvotes: 0
Reputation: 39092
According to the source code of the library, it seems it is actually averaging out the colors from the color palette of the picture
public async Task<QuantizedColor> GetColor(BitmapDecoder sourceImage, int quality = DefaultQuality,
bool ignoreWhite = DefaultIgnoreWhite)
{
var palette = await GetPalette(sourceImage, 3, quality, ignoreWhite);
var dominantColor = new QuantizedColor(new Color
{
A = Convert.ToByte(palette.Average(a => a.Color.A)),
R = Convert.ToByte(palette.Average(a => a.Color.R)),
G = Convert.ToByte(palette.Average(a => a.Color.G)),
B = Convert.ToByte(palette.Average(a => a.Color.B))
}, Convert.ToInt32(palette.Average(a => a.Population)));
return dominantColor;
}
In this particular case, I think setting ignoreWhite
to true
might return the actual black color, although it seems true
is indeed the default setting.
I recommend using the other public
method the library provides: GetPalette
, to see what is the actual color palette of this image. This should explain why you are getting this particular color.
var palette = await GetPalette(decoder);
Upvotes: 1