Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/282.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何将位图从内存转换为图像源,然后将其设置为画布在其上绘制的背景?_C#_Wpf_Bitmap_Background_Imagesource - Fatal编程技术网

C# 如何将位图从内存转换为图像源,然后将其设置为画布在其上绘制的背景?

C# 如何将位图从内存转换为图像源,然后将其设置为画布在其上绘制的背景?,c#,wpf,bitmap,background,imagesource,C#,Wpf,Bitmap,Background,Imagesource,我正在尝试拍摄整个桌面的屏幕截图,将其保存为位图,将位图转换为ImageSource,并将该ImageSource设置为画布的背景,我将在画布上绘制透明矩形 我尝试将图像直接添加到画布 我尝试添加图像作为画布的背景 我甚至尝试将图像作为背景添加到表单中,并使画布透明,但没有任何效果 我首先拍摄了一张桌面剪报并转换了图像: Bitmap-bitmapImage=新位图(SystemInformation.VirtualScreen.Width、SystemInformation.VirtualSc

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

  • 我尝试将图像直接添加到画布
  • 我尝试添加图像作为画布的背景
  • 我甚至尝试将图像作为背景添加到表单中,并使画布透明,但没有任何效果
  • 我首先拍摄了一张桌面剪报并转换了图像:

    Bitmap-bitmapImage=新位图(SystemInformation.VirtualScreen.Width、SystemInformation.VirtualScreen.Height);
    myNewImageSource=Miscellaneous.ImageSourceFromBitmap(bitmapImage);
    
    这是另一个线程上的转换函数:

    [DllImport(“gdi32.dll”,EntryPoint=“DeleteObject”)]
    [返回:Marshallas(UnmanagedType.Bool)]
    公共静态外部bool DeleteObject([In]IntPtr hObject);
    公共静态System.Windows.Media.ImageSource ImageSourceFromBitmap(位图bmp)
    {
    var handle=bmp.GetHbitmap();
    尝试
    {
    返回Imaging.CreateBitmapSourceFromHBitmap(handle、IntPtr.Zero、Int32Rect.Empty、BitmapSizeOptions.FromEmptyOptions());
    }
    最后{DeleteObject(handle);}
    }
    
  • 直接设置图像:
  • AddImageToCanvas(0,0,new System.Windows.Controls.Image(){Source=myNewImageSource});
    public void AddImageToCanvas(Int32 x,Int32 y,System.Windows.Controls.Image z)
    {
    图像持有人。儿童。添加(z);
    Canvas.SetLeft(z,x);
    Canvas.SetTop(z,y);
    }
    
  • 添加图像作为画布的背景:
  • imageHolder.Background=newimagebrush(){ImageSource=myNewImageSource};
    
  • 将图像设置为窗体背景并使画布透明:
  • Background=newimagebrush(){ImageSource=myNewImageSource}
    imageHolder.Background=newsolidcolorbush(System.Windows.Media.Color.FromRgb(0,0,0)){Opacity=0}
    //我尝试通过将不透明度设置为0和使用argb将alpha值设置为0来使背景透明,这两种方法都不起作用。
    

    我希望看到我的整个桌面的剪报作为画布的背景,但什么都没有发生,我没有得到任何错误。有时我会看到一个全黑的窗口。

    对于那些需要这个的人,我忘记了实际拍摄屏幕截图。以下是我的代码:

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

    你在哪里拍摄桌面截图?我看到你正在创建一个正确尺寸的位图,但我从来没有看到你用任何东西填充它。非常确定其他应用程序对位图做了更多的操作。你是对的,在你第一次发表评论后,我试图保存图像以查看输出,它是一个黑色矩形。我忘了设置图像,但我从上一个程序中获得了使其再次工作的代码。我忘了抄那个。感谢您的快速输入。