WPF 应用 - 颜色提取器

1. 功能

点击色图(如下图)的某一点,获取该点的颜色。

2. 实现

2.1 思路
  1. 获取图片的像素数组,数组保存每个点的 4 个通道,其中 3 个是 RGB 像素通道,1个是 Alpha 值
  2. 获取鼠标点击点在色图中的位置
  3. 根据位置从像素数组中获取 4 个通道值
  4. 根据几个通道值组成颜色值
2.2 代码:
<Grid MouseLeftButtonDown="Grid_MouseLeftButtonDown">
    <Grid.RowDefinitions>
        <RowDefinition Height="20"/>
        <RowDefinition Height="auto"/>
        <RowDefinition Height="20"/>
        <RowDefinition Height="auto"/>
    </Grid.RowDefinitions>
    <Image Grid.Row="1" Source="/Resources/Images/Cars/colorpicker1.png" Width="320" Height="240"/>
    <Image Grid.Row="3" Source="/Resources/Images/Cars/BMW.jpg" Width="630" Height="457"/>
</Grid>
private void Grid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    if (e.Source.GetType() != typeof(Image)) return;
            
    var pos = e.GetPosition((Image)e.Source);
    var img = ((Image)e.Source).Source as BitmapSource;

    if (pos.X > 0 && pos.Y > 0 && pos.X < img.PixelWidth && pos.Y < img.PixelHeight)
        SampleImageClick(img, pos);
}

protected void SampleImageClick(BitmapSource img, Point pos)
{
    int stride = img.PixelWidth * 4;
    int size = img.PixelHeight * stride;
    byte[] pixels = new byte[(int)size];

    img.CopyPixels(pixels, stride, 0);

    // Get pixel
    var x = (int)pos.X;
    var y = (int)pos.Y;

    int index = y * stride + 4 * x;

    byte red = pixels[index];
    byte green = pixels[index + 1];
    byte blue = pixels[index + 2];
    byte alpha = pixels[index + 3];

    Color color = Color.FromArgb(alpha, blue, green, red);
    string ColorText =  "#" + color.A.ToString("X2") + color.R.ToString("X2") + color.G.ToString("X2") + color.B.ToString("X2");
}

参考:

https://social.msdn.microsoft.com/Forums/vstudio/en-US/82a5731e-e201-4aaf-8d4b-062b138338fe/getting-pixel-information-from-a-bitmapimage?forum=wpf

posted @ 2021-03-15 22:41  鑫茂  阅读(436)  评论(0编辑  收藏  举报