Freigeben über


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