【问题标题】:Using Image control in WPF to display System.Drawing.Bitmap在 WPF 中使用 Image 控件显示 System.Drawing.Bitmap
【发布时间】:2010-11-10 05:58:57
【问题描述】:

如何在 WPF 中将内存中的 Bitmap 对象分配给 Image 控件?

【问题讨论】:

标签: c# wpf


【解决方案1】:

我用wpf 编写了一个程序,并使用数据库来显示图像,这是我的代码:

SqlConnection con = new SqlConnection(@"Data Source=HITMAN-PC\MYSQL;
                                      Initial Catalog=Payam;
                                      Integrated Security=True");

SqlDataAdapter da = new SqlDataAdapter("select * from news", con);

DataTable dt = new DataTable();
da.Fill(dt);

string adress = dt.Rows[i]["ImgLink"].ToString();
ImageSource imgsr = new BitmapImage(new Uri(adress));
PnlImg.Source = imgsr;

【讨论】:

  • 很好的答案,但我强烈建议将 Sql 对象包装在 using 语句中,以便在您使用完它们时将它们处理掉。
【解决方案2】:

磁盘文件容易,但内存中的位图更难。

System.Drawing.Bitmap bmp;
Image image;
...
MemoryStream ms = new MemoryStream();
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
ms.Position = 0;
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.StreamSource = ms;
bi.EndInit();

image.Source = bi;

Stealed here

【讨论】:

  • 谢谢,但是代码并没有关闭ms。我想你会使用stackoverflow.com/a/1069509/6116637
  • @lindexi 尽管MemoryStream 实现了IDisposable,但它不需要显式释放,因为它不包装任何非托管资源。它就像一个字节数组,最终会被 GC 收集。
【解决方案3】:

根据http://khason.net/blog/how-to-use-systemdrawingbitmap-hbitmap-in-wpf/

   [DllImport("gdi32")]
   static extern int DeleteObject(IntPtr o);

   public static BitmapSource loadBitmap(System.Drawing.Bitmap source)
   {
       IntPtr ip = source.GetHbitmap();
       BitmapSource bs = null;
       try
       {
           bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(ip, 
              IntPtr.Zero, Int32Rect.Empty, 
              System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
       }
       finally
       {
           DeleteObject(ip);
       }

       return bs;
   }

它获取 System.Drawing.Bitmap(来自 WindowsBased)并将其转换为 BitmapSource,它实际上可以用作 WPF 中 Image 控件的图像源。

image1.Source = YourUtilClass.loadBitmap(SomeBitmap);

【讨论】:

  • Thx Lars,但我做得更简单,BitmapImage bmpi = new BitmapImage(); bmpi.BeginInit(); bmpi.StreamSource = new MemoryStream(ByteArray); bmpi.EndInit(); image1.Source = bmpi;
  • 太棒了。您可以添加您的解决方案作为您自己问题的答案。
  • 我没有看到 BitmapImage.StreamSource 方法。 Prashant,你是不是打错字了?
  • 或者属性,就此而言。
  • 使用非托管句柄(例如 HBITMAP)时,请考虑使用 SafeHandles,请参阅 stackoverflow.com/questions/1546091/…
【解决方案4】:

您可以使用图像的 Source 属性。试试这个代码...

ImageSource imageSource = new BitmapImage(new Uri("C:\\FileName.gif"));

image1.Source = imageSource;

【讨论】:

  • 我有 Bitmap 对象,实际上它是从扫描设备生成的,所以我不能参考任何位置
猜你喜欢
  • 1970-01-01
  • 2010-11-14
  • 2019-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多