Sounds like you might have an issue with scaling.
If you are drawing the image using a different size that the source
Bitmap
, the you need to scale the coordinates accordingly.
Something like this might work for you:
using System;
using System.Drawing;
using System.Windows.Forms;
namespace GetPixelExample
{
public class Form1 : Form
{
private class ImageControl : Panel
{
private Bitmap bitmap = new Bitmap("C:\\alien.jpg");
public ImageControl()
{
MouseMove += new MouseEventHandler(HandleMouseMove);
}
private void HandleMouseMove(object sender, MouseEventArgs e)
{
double windowX = e.X;
double windowY = e.Y;
double controlWidth = Width;
double controlHeight = Height;
double imageWidth = bitmap.Width;
double imageHeight = bitmap.Height;
Color pixel = bitmap.GetPixel(
(int)(windowX * bitmap.Width / controlWidth),
(int)(windowY * bitmap.Height / controlHeight));
System.Diagnostics.Debug.WriteLine(pixel);
}
protected override void OnResize(EventArgs eventargs)
{
base.OnResize(eventargs);
Invalidate();
}
protected override void OnPaintBackground(PaintEventArgs pevent)
{
pevent.Graphics.DrawImage(bitmap, Bounds);
}
}
public Form1()
{
ImageControl control = new ImageControl();
control.Dock = DockStyle.Fill;
Controls.Add(control);
this.PerformLayout();
}
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}