0

I'm currently starting with an application using WinUI. It's about getting the color in a specific x,y coordinates of an image. I tried to use the BitmapImage to load the image. The problem is I don't have enough info on how to access it's pixel info like color. Anyone can help on this? thanks.

Expected result is to extract color of a specific pixel in an image using BitmapImage object.

keal24
  • 1
  • 2
  • 1
    Does this answer your question? [Finding specific pixel colors of a BitmapImage](https://stackoverflow.com/questions/1176910/finding-specific-pixel-colors-of-a-bitmapimage) – Andrew KeepCoding Feb 01 '23 at 12:11
  • 1
    You could use WinRT's SoftwareBitmap instead https://learn.microsoft.com/en-us/uwp/api/windows.graphics.imaging.softwarebitmap (and possibly WinUI3's SoftwareBitmapSource too) because it has buffer/pixel support (LockBuffer then WinRT's cast as IMemoryBufferByteAccess https://stackoverflow.com/questions/66147459/get-pointer-to-data-in-windows-ai-machinelearning-tensorfloat-from-c-sharp) – Simon Mourier Feb 01 '23 at 16:13

1 Answers1

0

Use WriteableBitmap.

A WriteableBitmap provides a BitmapSource that can be modified and that doesn't use the basic file-based decoding from the WIC. You can alter images dynamically and re-render the updated image.

See Images and image brushes for more information, and

The IBuffer returned by WriteableBitmap.PixelBuffer can't be written to directly. But you can use language-specific techniques to write to the underlying pixel content in the buffer.

WriteableBitmap.PixelBuffer code snippet which comes from XAML images sample shows how to get pixel data.

using (IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read)) 
{
    BitmapDecoder decoder = await BitmapDecoder.CreateAsync(fileStream); 
    // Scale image to appropriate size 
    BitmapTransform transform = new BitmapTransform() {  
        ScaledWidth = Convert.ToUInt32(Scenario4WriteableBitmap.PixelWidth), 
        ScaledHeight = Convert.ToUInt32(Scenario4WriteableBitmap.PixelHeight)
    }; 
    PixelDataProvider pixelData = await decoder.GetPixelDataAsync( 
        BitmapPixelFormat.Bgra8, // WriteableBitmap uses BGRA format 
        BitmapAlphaMode.Straight, 
        transform, 
        ExifOrientationMode.IgnoreExifOrientation, // This sample ignores Exif orientation 
        ColorManagementMode.DoNotColorManage
    ); 

    // An array containing the decoded image data, which could be modified before being displayed 
    byte[] sourcePixels = pixelData.DetachPixelData(); 

    // Open a stream to copy the image contents to the WriteableBitmap's pixel buffer 
    using (Stream stream = Scenario4WriteableBitmap.PixelBuffer.AsStream()) 
    { 
        await stream.WriteAsync(sourcePixels, 0, sourcePixels.Length); 
    }                     
}
YangXiaoPo-MSFT
  • 1,589
  • 1
  • 4
  • 22