Image是显示图片的控件,若要显示一张Bitmap的图片,必须转换成ImageSouce,并赋值给Souce,有如下几种方式:
A:
private ImageSource ToBitmapSourceA(Bitmap bitmap)
{
MemoryStream stream = new MemoryStream();
bitmap.Save(stream, ImageFormat.Bmp);
stream.Position = 0;
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.StreamSource = stream;
bitmapImage.EndInit();
return bitmapImage;
}
B:
[DllImport("gdi32")]
private static extern int DeleteObject(IntPtr o);
public ImageSource ToBitmapSourceB(Bitmap bitmap)
{
IntPtr ptr = bitmap.GetHbitmap(); //obtain the Hbitmap
BitmapSource bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(ptr, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
DeleteObject(ptr); //release the HBitmap
return bitmapSource;
}
C:
public ImageSource ToBitmapSourceC(Bitmap bitmap)
{
var bmpData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
BitmapSource bitmapSource = BitmapSource.Create(bitmap.Width, bitmap.Height, 96, 96, PixelFormats.Bgr24, myPalette, bmpData.Scan0, bitmap.Width * bitmap.Height * 3, bitmap.Width * 3);
bitmap.UnlockBits(bmpData);
return bitmapSource;
}
在我的电脑上测试:运行A需要5.2毫秒,B需2.6毫秒,C需1.2毫秒,显然C是最快的。
更何况如果用opencv获取摄像头数据的话,还不需要转换成Bitmap格式,直接用Mat.DataPointer就搞定了。
private ImageSource ToImageSourceD(Mat frame)
{
return BitmapSource.Create(frame.Width, frame.Height, 96, 96, PixelFormats.Bgr24, myPalette, frame.DataPointer, frame.Width * frame.Height * 3, frame.Width * 3);
}
是不是方便多了?
是不是方便多了?是不是方便多了?是不是方便多了?是不是方便多了?是不是方便多了?是不是方便多了?是不是方便多了?是不是方便多了?是不是方便多了?是不是方便多了?是不是方便多了?是不是方便多了?是不是方便多了?是不是方便多了?是不是方便多了?是不是方便多了?是不是方便多了?是不是方便多了?是不是方便多了?是不是方便多了?是不是方便多了?是不是方便多了?是不是方便多了?是不是方便多了?
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)
2015-02-01 第三方应用开发的一点心得