【发布时间】:2010-11-10 05:58:57
【问题描述】:
如何在 WPF 中将内存中的 Bitmap 对象分配给 Image 控件?
【问题讨论】:
-
stackoverflow.com/questions/94456/… 的完全重复,但我的回答没有泄露 HBitmap
如何在 WPF 中将内存中的 Bitmap 对象分配给 Image 控件?
【问题讨论】:
我用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;
【讨论】:
磁盘文件容易,但内存中的位图更难。
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;
【讨论】:
MemoryStream 实现了IDisposable,但它不需要显式释放,因为它不包装任何非托管资源。它就像一个字节数组,最终会被 GC 收集。
根据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);
【讨论】:
您可以使用图像的 Source 属性。试试这个代码...
ImageSource imageSource = new BitmapImage(new Uri("C:\\FileName.gif"));
image1.Source = imageSource;
【讨论】: