【C#】Bitmap使用汇总

发布时间 2023-10-17 14:55:46作者: 不溯流光

一、实现Bitmap和BitmapSource之间的转换

在Winform中使用BitmapSource须添加PresentationCore.dll、WindowsBase.dll、System.Xaml.dll

        /// <summary>
        /// 将 Bitmap 转化为 BitmapSource
        /// </summary>
        /// <param name="bmp"/>要转换的 Bitmap
        /// <returns>转换后的 BitmapSource</returns>
        public static BitmapSource ToBitmapSource(this System.Drawing.Bitmap bmp)
        {
            System.IntPtr hBitmap = bmp.GetHbitmap();
            try
            {
                return System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(hBitmap, System.IntPtr.Zero, System.Windows.Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
            }
            finally
            {
                DeleteObject(hBitmap);
            }
        }

 参考:http://www.firstsolver.com/wordpress/?p=3462/

二、加载16位灰度图

        private Bitmap DisplayImage16(string fileName)
        {
            ///须添加PresentationCore.dll、WindowsBase.dll、System.Xaml.dll
            try
            {
                Bitmap bp;
                BinaryReader br = new BinaryReader(File.Open(fileName, FileMode.Open));
                long iTotalSize = br.BaseStream.Length;
                int iNumberOfPixels = (int)(iTotalSize / 2);

                int bitsPerPixel = 16;
                int stride = (picweight * bitsPerPixel + 7) / 8;
                ushort[] pix16 = new ushort[iNumberOfPixels];

                for (int i = 0; i < iNumberOfPixels; ++i)
                {
                    ushort pixShort = (ushort)(br.ReadUInt16());
                    pix16[i] = pixShort;
                }
                System.Windows.Media.Imaging.BitmapSource bmps = System.Windows.Media.Imaging.BitmapSource.Create(picweight, picheight, 96, 96, System.Windows.Media.PixelFormats.Gray16, null,
                       pix16, stride);

                bp = ToBitmap(bmps);
                return bp;
            }
            catch (Exception e)
            {
                return null;
            }
        }