如何将位图从内存转换为 ImageSource,然后将其设置为 canvas 的背景以在其上绘制?

How to convert a Bitmap from memory to an ImageSource then set it as Background for a canvas to draw over it?

我正在尝试截取整个桌面的屏幕截图,将其保存为位图,将位图转换为 ImageSource 并将该 ImageSource 设置为 Canvas 我要在其上的背景绘制透明矩形。

  1. 我尝试将图像直接添加到 Canvas。
  2. 我尝试将图像添加为 Canvas 的背景。
  3. 我什至尝试将图像作为背景添加到表单中并使 canvas 透明,但没有任何效果。

我首先截取桌面截图并转换图像:

Bitmap bitmapImage = new Bitmap(SystemInformation.VirtualScreen.Width, SystemInformation.VirtualScreen.Height);
myNewImageSource = Miscellaneous.ImageSourceFromBitmap(bitmapImage);

这是在另一个线程上找到的转换函数:

[DllImport("gdi32.dll", EntryPoint = "DeleteObject")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool DeleteObject([In] IntPtr hObject);

public static System.Windows.Media.ImageSource ImageSourceFromBitmap(Bitmap bmp)
{
    var handle = bmp.GetHbitmap();
    try
    {
        return Imaging.CreateBitmapSourceFromHBitmap(handle, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
    }
    finally { DeleteObject(handle); }
}
  1. 直接设置图片:
AddImageToCanvas(0, 0, new System.Windows.Controls.Image() { Source = myNewImageSource });

public void AddImageToCanvas(Int32 x, Int32 y, System.Windows.Controls.Image z)
{
    imageHolder.Children.Add(z);
    Canvas.SetLeft(z, x);
    Canvas.SetTop(z, y);
}
  1. 添加图像作为 canvas 的背景:
imageHolder.Background = new ImageBrush(){ ImageSource = myNewImageSource };
  1. 将图像设置为表单背景并使 canvas 透明:
Background = new ImageBrush(){ ImageSource = myNewImageSource }
imageHolder.Background = new SolidColorBrush(System.Windows.Media.Color.FromRgb(0, 0, 0)) { Opacity = 0 }
//I tried making the background transparent by both setting the Opacity to 0 and trying with argb to set the alpha value to 0, neither worked.

我希望看到整个桌面的截图作为 canvas 的背景,但什么也没有发生,我也没有收到任何错误。有时我只是得到一个完全黑色的 Window.

对于那些需要这个的人,我真的忘记截图了。这是我的代码:

Graphics g = Graphics.FromImage(bitmapImage);
g.CopyFromScreen(0, 0, 0, 0, bitmapImage.Size);