Returns the BitmapSource pixels as a 2-dimensional array - CSharp System.Windows.Media.Imaging

CSharp examples for System.Windows.Media.Imaging:BitmapSource

Description

Returns the BitmapSource pixels as a 2-dimensional array

Demo Code


using System.IO;//from w  w  w.ja  v a2s.  c  om
using System.Windows.Media;
using System.Runtime.InteropServices;
using System.Windows.Media.Imaging;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System;

public class Main{
        /// <summary>
        /// Returns the pixels as a 2-dimensional array
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static PixelColor[,] GetPixels(this BitmapSource source)
        {
            if (source.Format != PixelFormats.Bgra32)
            {
                source = new FormatConvertedBitmap(source, 
                    PixelFormats.Bgra32, null, 0);
            }

            int width = source.PixelWidth;
            int height = source.PixelHeight;
            PixelColor[,] result = new PixelColor[width, height];

            CopyPixels(source, result, width * 4, 0);
            return result;
        }
        private static void CopyPixels(BitmapSource source, PixelColor[,] pixels, 
            int stride, int offset)
        {
            var height = source.PixelHeight;
            var width = source.PixelWidth;
            var pixelBytes = new byte[height * width * 4];
            source.CopyPixels(pixelBytes, stride, 0);
            int y0 = offset / width;
            int x0 = offset - width * y0;
            for (int y = 0; y < height; y++)
                for (int x = 0; x < width; x++)
                    pixels[x + x0, y + y0] = new PixelColor
                    {
                        Blue = pixelBytes[(y * width + x) * 4 + 0],
                        Green = pixelBytes[(y * width + x) * 4 + 1],
                        Red = pixelBytes[(y * width + x) * 4 + 2],
                        Alpha = pixelBytes[(y * width + x) * 4 + 3],
                    };
        }
}

Related Tutorials