Find the transparent pixels in an image – WPF

Extracted from: http://random.tonywilliams.me.uk/post/392778744/find-the-transparent-pixels-in-an-image-wpf

The other day I had to create an image element that contained a png with transparent sections and have it display a hand cursor when the mouse was over the opaque sections.

The first thing I tried (and failed) was to have an image element with the cursor property set to “Hand” like so:

<Image Source="{Binding SomeImage}" Cursor="Hand" />

That obviously never worked so I was forced to look at each individual pixel and see if it was transparent. What I ended up with was a function that generated a bunch of coordinates.

This is that function:

private static Dictionary<Point, object> FindTransparentPixelCoordinates(BitmapSource source)
{
  var points = new Dictionary<Point, object>();

  // Convert the source if the pixel format is not what we expect
  if (source.Format != PixelFormats.Bgra32)
  {
    source = new FormatConvertedBitmap(source, PixelFormats.Bgra32, null, 0);
  }

  int width = source.PixelWidth;
  int height = source.PixelHeight;
  var bytes = new byte[width * height * 4];

  source.CopyPixels(bytes, width * 4, 0);

  var position = 0;

  for (var y = 0; y < height; y++)
  {
    for (var x = 0; x < width; x++)
    {
      var byteOffset = position;

      // The pixel format is stored as 32-bits (4 bytes) with the last byte being the alpha

      if (bytes[byteOffset + 3] == 0)
      {
        points.Add(new Point(x, y), null);
      }

      position += 4;
    }
  }

  return points;
}

Leave a Reply