天天看點

wpf BitmapSource轉byte數組;BitmapSource轉Bitmap,支援8位圖的轉換

先将bitmapSource 轉成數組,再進行鎖記憶體操作,複制内容到bitmap

public static System.Drawing.Bitmap ToBitmap(BitmapSource source)
        {

            if (source == null) return null;
            System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap((int)source.Width, (int)source.Height);
            int width = bitmap.Width;
            int height = bitmap.Height;

            System.Drawing.Rectangle rect = new System.Drawing.Rectangle(0, 0, width, height);
            System.Drawing.Imaging.BitmapData bmpData = bitmap.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, bitmap.PixelFormat);
            IntPtr ptr = bmpData.Scan0;

            byte[] rgbValues = BitmapImageToByteArray(source as BitmapImage);

            System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, rgbValues.Length);
            bitmap.UnlockBits(bmpData);

            return bitmap;

        }

        /// <summary>
        /// BitmapImage轉數組
        /// </summary>
        /// <param name="bmp"></param>
        /// <returns></returns>
        public static byte[] BitmapImageToByteArray(BitmapSource bmp)
        {
            Int32 PixelHeight = bmp.PixelHeight; // 圖像高度
            Int32 PixelWidth = bmp.PixelWidth;   // 圖像寬度
            Int32 Stride = PixelWidth << 2;         // 掃描行跨距
            Byte[] Pixels = new Byte[PixelHeight * Stride];
            if (bmp.Format == PixelFormats.Bgr32 || bmp.Format == PixelFormats.Bgra32)
            {   // 拷貝像素資料
                bmp.CopyPixels(Pixels, Stride, 0);
            }
            else
            {   // 先進行像素格式轉換,再拷貝像素資料
                new FormatConvertedBitmap(bmp, PixelFormats.Bgr32, null, 0).CopyPixels(Pixels, Stride, 0);
            }
            return Pixels;

        }