Wpf ImageSource对象与Bitmap对象的互相转换

发布时间 2023-12-21 15:49:39作者: WebEnh
    1. Bitmap to ImageSource
      将得到的Bitmap对象转换为wpf常用的Imagesource对象
BitmapSource bs = Imaging.CreateBitmapSourceFromHBitmap(bmp.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());

得到的BitmapSource是Imagesource的子类

  1. ImageSource to Bitmap
首先得到ImageSource对象_imagesource

System.IO.MemoryStream ms = new System.IO.MemoryStream();
BmpBitmapEncoder encoder = new BmpBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create((BitmapSource)_imagesource));
encoder.Save(ms);

Bitmap bp = new Bitmap(ms);
ms.Close();