How to detect a png picture file's brightness/lightness in UWP

0

In my project, a background picture is fetched from cloud. But some picture is too light, and some are dark. So I need to detect the background picture's brightness and hence to decide whether to add a mask.

I searched the solution on Google and found most solution is for WPF and using Bitmap. But they are forbidden in UWP.

Like below code. When I run the UWP project, VS will report error:

  System.PlatformNotSupportedException
  HResult=0x80131539
  Message=System.Drawing is not supported on this platform.

So how to detect it in UWP?

    private static float GetBrightness(string url)
    {
        Bitmap bitmap = new Bitmap(url);
        var colors = new List<Color>();
        for (int x = 0; x < bitmap.Size.Width; x++)
        {
            for (int y = 0; y < bitmap.Size.Height; y++)
            {
                colors.Add(bitmap.GetPixel(x, y));
            }
        }

        float imageBrightness = colors.Average(color => color.GetBrightness());
        return imageBrightness;
    }
c#
uwp
asked on Stack Overflow Jul 7, 2020 by Tom Xue

1 Answer

0

This works:

private async Task<float> GetBrightness(string url)
{
    WebRequest myrequest = WebRequest.Create(url);
    WebResponse myresponse = myrequest.GetResponse();
    var imgstream = myresponse.GetResponseStream();

    // Try to create SoftwareBitmap
    MemoryStream ms = new MemoryStream();
    imgstream.CopyTo(ms);
    var dec = await BitmapDecoder.CreateAsync(ms.AsRandomAccessStream());

    var data = await dec.GetPixelDataAsync();

    var bytes = data.DetachPixelData();


    var colors = new List<Color>();
    for (int x = 0; x < dec.PixelWidth; x++)
    {
        for (int y = 0; y < dec.PixelHeight; y++)
        {
            colors.Add(GetPixel(bytes, x, y, dec.PixelWidth, dec.PixelHeight));
        }
    }

    float imageBrightness = colors.Average(color => color.GetBrightness());
    return imageBrightness;

}

public Color GetPixel(byte[] pixels, int x, int y, uint width, uint height)
{
    int i = x;
    int j = y;
    int k = (i * (int)width + j) * 3;
    var r = pixels[k + 0];
    var g = pixels[k + 1];
    var b = pixels[k + 2];
    return Color.FromArgb(0, r, g, b);
}

Source1, Source2

answered on Stack Overflow Jul 7, 2020 by Alamakanambra

User contributions licensed under CC BY-SA 3.0