WPF(C#)中Bitmap與BitmapImage相互轉換


一、WPF的Image控件中設置ImageSource

image1.Source = new BitmapImage(new Uri(@"image file path", Urikind.RelativeOrAbsolute));

還可以使用:

System.IO.FileStream fs = new System.IO.FileStream(filepath, System.IO.FileMode.Open, System.IO.FileAccess.Read);

byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length);
fs.Close(); fs.Dispose();
System.IO.MemoryStream ms = new System.IO.MemoryStream(buffer);
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.StreamSource = ms;
bitmapImage.CacheOption = BitmapCacheOption.OnLoad; bitmapImage.EndInit();
ms.Dispose();
image1.Source = bitmapImage;

還可以使用:

BitmapImage bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.UriSource = new Uri(szPath);//szPath為圖片的全路徑
bitmapImage.EndInit();
bitmapImage.Freeze();
image1.Source = bitmapImage;

二、Bitmap轉BitmapImage 
先將Bitmap儲存成memorystream,然后指定給BitmapImage

private BitmapImage BitmapToBitmapImage(System.Drawing.Bitmap bitmap)
{
BitmapImage bitmapImage = new BitmapImage();
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
  bitmap.Save(ms, bitmap.RawFormat);
  bitmapImage.BeginInit();
  bitmapImage.StreamSource = ms;
  bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
  bitmapImage.EndInit();
  bitmapImage.Freeze();
}
  return bitmapImage;
}

image1.Source = BitmapToBitmapImage(bitmap);

三、Bitmap轉BitmapSource

/*-------------------------------------------------------------------------
//Imaging.CreateBitmapSourceFromHBitmap方法,基於所提供的非托管位圖和調色板信息的指針,
//返回一個托管的BitmapSource
---------------------------------------------------------------------------*/
Bitmap bitmap = CaptureScreen.GetDesktopImage();
IntPtr ip = bitmap.GetHbitmap();//從GDI+ Bitmap創建GDI位圖對象

BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(ip, IntPtr.Zero, Int32Rect.Empty,
System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());

image1.Source = bitmapSource;

四、BitmapSource轉Bitmap

BitmapSource m = (BitmapSource)image1.Source;

System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(m.PixelWidth, m.PixelHeight, System.Drawing.Imaging.PixelFormat.Format32bppPArgb); 

System.Drawing.Imaging.BitmapData data = bmp.LockBits(
new System.Drawing.Rectangle(System.Drawing.Point.Empty, bmp.Size), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppPArgb); 

m.CopyPixels(Int32Rect.Empty, data.Scan0, data.Height * data.Stride, data.Stride); bmp.UnlockBits(data);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM