zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    ISBN号码
    计数问题
    小玉在游泳
    数字反转
    单调队列(学习笔记)
    LCA(学习笔记)
    emacs配置文件
    线段树(学习笔记)
    RMQ问题 ST算法(学习笔记)
    Lucas卢卡斯定理(学习笔记)
  • 原文地址:https://www.cnblogs.com/MichaelLoveSna/p/14496942.html
Copyright © 2011-2022 走看看