C# 在WPF中使用Image控件显示System.Drawing.Bitmap

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1118496/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 08:37:17  来源:igfitidea点击:

Using Image control in WPF to display System.Drawing.Bitmap

c#wpf

提问by Prashant Cholachagudda

How do I assign an in-memory Bitmapobject to an Imagecontrol in WPF ?

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

采纳答案by Lars Truijens

You can use the Source property of the image. Try this code...

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

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

image1.Source = imageSource;

回答by Lars Truijens

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

根据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;
   }

It gets System.Drawing.Bitmap (from WindowsBased) and converts it into BitmapSource, which can be actually used as image source for your Image control in WPF.

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

image1.Source = YourUtilClass.loadBitmap(SomeBitmap);

回答by Badiboy

It's easy for disk file, but harder for Bitmap in memory.

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

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

这里偷的

回答by Mr47

I wrote a program with wpfand used Database for showing images and this is my code:

我编写了一个程序,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;