[英]how to use bitmap as source for image in wpf
在我的应用程序中,我想使用名为myBitmap的位图在图像框上绘制一个矩形。 问题是如何在C#Wpf中使用System.Drawing.bitMap作为图像源。
private void MyRectangle(System.Drawing.Point p1, System.Drawing.Point p2)
{
int var1,var2;
var1 = Convert.ToInt16(image1.Width);
var2 = Convert.ToInt16(image1.Height);
System.Drawing.Bitmap myBitmap = new System.Drawing.Bitmap(var1,var2);
using (Graphics g = Graphics.FromImage(myBitmap))
{
g.Clear(Color.LightBlue);
g.DrawRectangle(new Pen(Brushes.Red),p1.X, p1.Y, p2.X - p1.X, p2.Y - p1.Y);
}
// this.image1.Source = myBitmap;
}
将其转换为BitmapSource,使用BitmapSource作为Image控件的Source。
public static BitmapSource ConvertToBitmapSource(Bitmap bitmap)
{
if (bitmap == null)
return null;
//BitmapImage b=new BitmapImage();
BitmapSource bitSrc = null;
var hBitmap = IntPtr.Zero;
try
{
hBitmap = bitmap.GetHbitmap();
bitSrc = Imaging.CreateBitmapSourceFromHBitmap(
hBitmap,
IntPtr.Zero,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
}
catch (Win32Exception)
{
bitSrc = null;
}
catch (ArgumentException)
{
if (hBitmap != IntPtr.Zero)
DeleteObject(hBitmap);
hBitmap = IntPtr.Zero;
}
catch
{
if (hBitmap != IntPtr.Zero)
DeleteObject(hBitmap);
bitSrc = null;
hBitmap = IntPtr.Zero;
}
finally
{
//bitmap.Dispose();
if (hBitmap != IntPtr.Zero)
DeleteObject(hBitmap);
}
return bitSrc;
}
[DllImport("gdi32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool DeleteObject(IntPtr hObject);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.