当前位置: 首页 > 编程语言 > C#

在WPF中显示Drawing.Image分享

时间:2023-04-10 22:32:10 C#

在WPF中显示Drawing.Image我有一个System.Drawing.Image的实例。如何在我的WPF应用程序中显示它?我尝试使用img.Source但这不起作用。我遇到了同样的问题,并结合了几个答案来解决它。System.Drawing.Bitmapbmp;形象形象;...使用(varms=newMemoryStream()){bmp.Save(ms,System.Drawing.Imaging.ImageFormat.Png);ms.Position=0;varbi=newBitmapImage();bi.BeginInit();bi.CacheOption=BitmapCacheOption.OnLoad;bi.StreamSource=ms;bi.EndInit();}image.Source=bi;//bmp.Dispose();//如果不进一步使用bmp。感谢来自这个问题和答案的@Peter要将图像加载到WPF图像控件中,您需要一个System.Windows.Media.ImageSource。您需要将Drawing.Image对象转换为ImageSource对象:publicstaticBitmapSourceGetImageStream(ImagemyImage){varbitmap=newBitmap(myImage);IntPtrbmpPt=bitmap.GetHbitmap();BitmapSource位图源=System.Windows.Interop.Imaging。CreateBitmapSourceFromHBitmap(bmpPt,IntPtr.Zero,Int32Rect.Empty,BitmapSizeOptions.FromEmptyOptions());//冻结bitmapSource并清除内存以避免内存泄漏bitmapSource.Freeze();删除对象(bmpPt);returnbitmapSource.Delete}对象方法;[DllImport("gdi32.dll")][返回:MarshalAs(UnmanagedType.Bool)]internalstaticexternboolDeleteObject(IntPtrvalue);如果您使用转换器,您实际上可以绑定到Image对象。您只需要创建一个将Image转换为BitmapSource的IValueConverter。我在转换器中使用了AlexDrenea的示例代码来完成实际工作。[ValueConversion(typeof(Image),typeof(BitmapSource))]publicclassImageToBitmapSourceConverter:IValueConverter{[DllImport("gdi32.dll")][返回:MarshalAs(UnmanagedType.Bool)]internalstaticexternboolDeleteObject(IntPtrvalue);publicobjectConvert(objectvalue,TypetargetType,objectparameter,System.Globalization.CultureInfoculture){ImagemyImage=(Image)value;varbitmap=newBitmap(myImage);IntPtrbmpPt=bitmap.GetHbitmap();BitmapSourcebitmapSource=System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(bmpPt,IntPtr.Zero,Int32Rect.Empty,BitmapSizeOptions.FromEmptyOptions());//冻结bitmapSource并清除内存以避免内存泄漏bitmapSource.Freeze();删除对象(bmpPt);返回位图源;}publicobjectConvertBack(objectvalue,TypetargetType,objectparameter,System.Globalization.CultureInfoculture){thrownewNotImplementedException();}}在您的XAML中,您需要添加转换工具。以上就是C#学习教程:在WPF中显示Drawing.Image共享的所有内容。如果对你有用,需要进一步了解C#学习教程,希望大家多多关注。本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: