예제 #1
0
        public static WriteableBitmap ConvertToGrayScale(ZoomBorder border, BitmapImage source, Int32Rect roi)
        {
            WriteableBitmap wb = new WriteableBitmap(source);

            int[] grayPixels   = new int[wb.PixelWidth * wb.PixelHeight];
            int   widthInBytes = 4 * wb.PixelWidth;

            wb.CopyPixels(grayPixels, widthInBytes, 0);

            //foreach (int x in index)
            for (int x = 0; x < wb.PixelWidth * wb.PixelHeight; x++)
            {
                // get the pixel
                int pixel = grayPixels[x];

                // get the component
                int red   = (pixel & 0x00FF0000) >> 16;
                int blue  = (pixel & 0x0000FF00) >> 8;
                int green = (pixel & 0x000000FF);

                // get the average
                int average = (byte)((red + blue + green) / 3);

                // assign the gray values keep the alpha
                unchecked
                {
                    grayPixels[x] = (int)((pixel & 0xFF000000) | (average << 16) | (average << 8) | average);
                }
            }

            if (roi.Height > 0 && roi.Width > 0)
            {
                roi = RoiToPixel(border, source, roi);
                wb.WritePixels(roi, grayPixels, widthInBytes, (roi.Y * source.PixelWidth) + roi.X);
            }
            else
            {
                wb.WritePixels(new Int32Rect(0, 0, wb.PixelWidth, wb.PixelHeight), grayPixels, widthInBytes, 0);
            }

            return(wb);
        }