I have a BitmapIamge , this is png 100 by 100 pixels. I searched the entire Internet and found the copyPixels method, only I don’t know how to use it. Errors come out of me, the color is always black. Can anyone write a working method to get the color from a BitmapImage ?

    1 answer 1

    You must first convert BitmapImage to Bitmap

      private static Bitmap BitmapImage2Bitmap(BitmapSource bitmapImage) { using (var outStream = new MemoryStream()) { BitmapEncoder enc = new BmpBitmapEncoder(); enc.Frames.Add(BitmapFrame.Create(bitmapImage)); enc.Save(outStream); var bitmap = new Bitmap(outStream); return bitmap; } } 

    And then get the right pixel:

      var url = new Uri("D:\\1.png"); var bi = new BitmapImage(url); var bm = BitmapImage2Bitmap(bi); var pixel = bm.GetPixel(x, y); 

    Where x and y - coordinates of the pixel from the upper left corner. Color in RGB format will be available from the fields pixel.R pixel.G pixel.B for red, green, and blue, respectively, and pixel.A , for the alpha channel.

    • Imported System.Drawing, but there is no Bitmap type, this is in WPF. How is that? - Minebot pm
    • In the sense of using System.Drawing; in the title added? And links to the assembly in the project added? - Sergey
    • Link to the assembly? In the referenses or what? - Minebot
    • Yes, precisely there. - Sergey
    • I've done everything. Thank you very much - Minebot