Search code examples
c#colorsuwpcolor-thief

How to Use Color Thief With UWP


I loading images source from internet and I need this images dominant color. Forexample this image and then found color thief but I cant understand.

I using this method but I think it's wrong.

BitmapDecoder BMD = new BitmapDecoder("https://yt3.ggpht.com/-cYK4gMKhvV0/AAAAAAAAAAI/AAAAAAAAAAA/8znlvBw-Wos/s100-c-k-no-mo-rj-c0xffffff/photo.jpg");
var colorThief = new ColorThief();
await colorThief.GetColor(BMD);

How can I do it?


Solution

  • It is right that the GetColor method of ColorThief requires a BitmapDecoder parameter. But BitmapDecode is not created by the way you are trying. BitmapDecoder can be created by IRandomAccessStream according to CreateAsync() method, cannot be created directly by a Uri. So you need a RandomAccessStream object firstly. This can be done by creating a RandomAccessStreamReference by RandomAccessStreamReference.CreateFromUri(Uri), and then open and read it. A complete demo by using the ColorThief is as follows you can reference:

    Uri imageUri = new Uri("https://yt3.ggpht.com/-cYK4gMKhvV0/AAAAAAAAAAI/AAAAAAAAAAA/8znlvBw-Wos/s100-c-k-no-mo-rj-c0xffffff/photo.jpg");
    RandomAccessStreamReference random = RandomAccessStreamReference.CreateFromUri(imageUri);
    using (IRandomAccessStream stream = await random.OpenReadAsync())   
    {
        //Create a decoder for the image
        var decoder = await BitmapDecoder.CreateAsync(stream);
        var colorThief = new ColorThief();
        var color = await colorThief.GetColor(decoder);       
    }