我如何在WPF中将内存中的Bitmap
对象分配给Image
控件?
根据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;
}
它获取来自WindowsBased的System.Drawing.Bitmap并将其转换为BitmapSource,这可以实际用作WPF中Image控件的图像源。
image1.Source = YourUtilClass.loadBitmap(SomeBitmap);
对于磁盘文件来说很容易,但对于内存中的位图则更加困难。
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 回收。 - kennyzxImageSource imageSource = new BitmapImage(new Uri("C:\\FileName.gif"));
image1.Source = imageSource;
我用 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;