2010-05-24 85 views
1

目前为止,我发现的唯一方法是System.Drawing.Bitmap.GetPixel(),但微软对System.Drawing发出警告,这让我怀疑这是否是“老办法” 。有没有其他的选择?在WPF应用程序中使用C#确定位图中像素的颜色


这里是微软说,有关的System.Drawing命名空间是什么。我还注意到,当我创建一个新的WPF项目时,System.Drawing程序集不会自动添加到引用中。

System.Drawing命名空间

System.Drawing命名空间提供访问GDI +基本图形功能。 System.Drawing.Drawing2D,System.Drawing.Imaging和System.Drawing.Text命名空间中提供了更高级的功能。

Graphics类提供了绘制到显示设备的方法。诸如Rectangle和Point的类封装了GDI +原语。 Pen类用于绘制直线和曲线,而从抽象类Brush派生的类用于填充形状的内部。

注意

System.Drawing命名空间中的类不支持Windows或ASP.NET服务中使用。试图从这些应用程序类型中使用这些类可能会产生意想不到的问题,例如服务性能下降和运行时异常。

- http://msdn.microsoft.com/en-us/library/system.drawing.aspx

+0

哪些警告?你可以在问题中与我们分享吗? – 2010-05-24 05:09:34

+0

@Shay,完成。看到我编辑的问题。 – devuxer 2010-05-24 05:27:25

+0

据我所见,他们只告诉你不要在服务中使用System.Drawing(这是有道理的)。在WPF应用程序中使用它没有任何问题。 – 2010-05-24 09:22:39

回答

1

this question和一个很好的解释最多的回答。但要回答你的问题,使用System.Drawing.Bitmap.GetPixel()方法没有任何错误或“旧”。

2

您可以使用此代码

public Color GetPixel(BitmapSource bitmap, int x, int y) 
    { 
     Debug.Assert(bitmap != null); 
     Debug.Assert(x >= 0); 
     Debug.Assert(y >= 0); 
     Debug.Assert(x < bitmap.PixelWidth); 
     Debug.Assert(y < bitmap.PixelHeight); 
     Debug.Assert(bitmap.Format.BitsPerPixel >= 24); 

     CroppedBitmap cb = new CroppedBitmap(bitmap, new Int32Rect(x, y, 1, 1)); 
     byte[] pixel = new byte[bitmap.Format.BitsPerPixel/8]; 
     cb.CopyPixels(pixel, bitmap.Format.BitsPerPixel/8, 0); 
     return Color.FromRgb(pixel[2], pixel[1], pixel[0]); 
    } 
相关问题