简体   繁体   English

从 WINUI 应用程序中的 BitmapImage 检索特定像素颜色

[英]Retreiving specific pixel color from a BitmapImage in WINUI application

I'm currently starting with an application using WinUI.我目前正在开始使用 WinUI 的应用程序。 It's about getting the color in a specific x,y coordinates of an image.它是关于获取图像特定 x,y 坐标中的颜色。 I tried to use the BitmapImage to load the image.我尝试使用BitmapImage加载图像。 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.预期结果是使用BitmapImage object 提取图像中特定像素的颜色。

Use WriteableBitmap .使用WriteableBitmap

A WriteableBitmap provides a BitmapSource that can be modified and that doesn't use the basic file-based decoding from the WIC. WriteableBitmap 提供了一个可以修改的 BitmapSource,它不使用来自 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. WriteableBitmap.PixelBuffer 返回的 IBuffer 不能直接写入。 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.来自XAML 图像示例WriteableBitmap.PixelBuffer代码片段显示了如何获取像素数据。

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); 
    }                     
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM