Mouse Events and Reading Pixel Information with csXImage in C#

The demo application for csXImage includes an option to display information about individual pixels. This makes use of the 'OnMouseMove' event of the control to trigger C# code when the mouse cursor is positioned over an image. The information about the colour of the pixel under the mouse pointer is then read and displayed.

When the pixel information option is activated in the C# demo (using 'Tools/Pixel Info' from the menu), a cross-hair cursor is displayed when the mouse pointer is over the image. Pixel information is then read and displayed, as in the screenshot below.

Reading pixel data from an image using C#

In using this event to provide pixel data we have two problems to consider: (1) The event is fired whenever the cursor is over the control, even if it is not over the image. In these cases we do not want information displaying or the cursor changing. (2) The image may be scrolled, which means the X and Y co-ordinates returned by the OnMouseMove event will not correspond to the co-ordinates of the pixel in the image.

csXImage provides the ConvertEventXY method, which deals with these issues. It takes the mouse coordinates as input parameters and returns the coordinates on the image as output parameters. If the mouse is over a scrollbar, the output parameters both return -1.

The C# code used in this example is listed below:

private void axImageBox1_OnMouseMove(object sender,
    AxcsXImageTrial.IImageBoxEvents_OnMouseMoveEvent e)
{
  Color pixelCol;
  int xImage, yImage;
  if (mnuToolsPixelInfo.Checked)
  {
    axImageBox1.ConvertEventXY(e.x, e.y, out xImage, out yImage);
    if (xImage != -1)
    {
      fMain.ActiveForm.Cursor = Cursors.Cross;
      lblPixelX.Text = "X: " + xImage.ToString();
      lblPixelY.Text = "Y: " + yImage.ToString();
      pixelCol = axImageBox1.get_PixelColor(xImage, yImage);
      lblPixelRed.Text = "Red: " + pixelCol.R.ToString();
      lblPixelGreen.Text = "Green: " + pixelCol.G.ToString();
      lblPixelBlue.Text = "Blue: " + pixelCol.B.ToString();
      lblPixelCol.BackColor = pixelCol;
    }
    else
    {
      fMain.ActiveForm.Cursor = Cursors.Default;
      lblPixelX.Text = "X: n/a";
      lblPixelY.Text = "Y: n/a";
      lblPixelRed.Text = "Red: n/a";
      lblPixelGreen.Text = "Green: n/a";
      lblPixelBlue.Text = "Blue: n/a";
      lblPixelCol.BackColor = fMain.ActiveForm.BackColor;
    }
  }
}

Using this code, the cursor can be moved over the image, with information about the colour of the pixel under the mouse cursor displayed alongside, as in the screenshot above.

<<Previous page  Next page>>

Cookies

This site uses cookies for functionality, traffic analysis and for targeted advertising. Click the Accept button to accept our Cookie Policy. The Cookie Policy page offers configuration for a reduced set of cookies for this site.