How to: Convert an Image to Grayscale


I ran across an issue where I wanted to convert an Image in a Windows Store app  to grayscale and could not find a great example.  So… here is one for you to try!

 private async Task imageToGrayscale(Image src, Image dest)
        {
            RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap();
            //Get existing src pixels in a Byte[] (always is BRGA formate
            await renderTargetBitmap.RenderAsync(src);
            IBuffer pixelSrc = await renderTargetBitmap.GetPixelsAsync();
            Byte[] destBytes = new Byte[pixelSrc.Length];

            for (int i = 0; i < pixelSrc.Length; i += 4)
            {
                double b = (double)pixelSrc.GetByte((uint)i) / 255.0;
                double g = (double)pixelSrc.GetByte((uint)i+1) / 255.0;
                double r = (double)pixelSrc.GetByte((uint)i+2) / 255.0;

                byte a = pixelSrc.GetByte((uint)i + 3);

                double e = (0.21 * r + 0.71 * g + 0.07 * b) * 255;
                byte f = Convert.ToByte(e);

                destBytes[i] = f;
                destBytes[i + 1] = f;
                destBytes[i + 2] = f;
                destBytes[i + 3] = a;

            }

            WriteableBitmap destWB = new WriteableBitmap(renderTargetBitmap.PixelWidth, renderTargetBitmap.PixelHeight);
            using (Stream pixelStream = destWB.PixelBuffer.AsStream()) {
                pixelStream.Seek(0, SeekOrigin.Begin);
                pixelStream.Write(destBytes, 0, destBytes.Length);
                destWB.Invalidate();

            }
            destImage.Source = destWB;

        }

If you like it, drop me a note of thanks!

Comments (4)

  1. Alan Tatourian says:

    You can try this:

    code.msdn.microsoft.com/…/RGBA-to-Gray-image-e07dd9f5

    You can convert the code into parallel_for and then try using C++ AMP,

  2. Eugene_Astafiev says:

    Great job! Thanks for sharing the code! 🙂

  3. also see this related Getting Started with Image Processing Code Sample: code.msdn.microsoft.com/Getting-Started-with-Image-74a37d8b

    hope this helps as well 🙂

Skip to main content