Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/262.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#/WPF-使用位图/SystemArgumentException错误_C#_Wpf_Bitmap - Fatal编程技术网

C#/WPF-使用位图/SystemArgumentException错误

C#/WPF-使用位图/SystemArgumentException错误,c#,wpf,bitmap,C#,Wpf,Bitmap,基本上,我需要从现有位图(this.Document.bitmap)创建一个新位图,然后用同一属性中的新位图替换现有位图。我还希望处置此克隆可能导致的任何额外内存,但我收到此错误 using块之外的语句导致抛出此异常,我不知道为什么。帮忙 System.Drawing.dll中发生类型为“System.ArgumentException”的未处理异常 using (Bitmap b = this.Document.Bitmap.Clone(new RectangleF()

基本上,我需要从现有位图(this.Document.bitmap)创建一个新位图,然后用同一属性中的新位图替换现有位图。我还希望处置此克隆可能导致的任何额外内存,但我收到此错误

using块之外的语句导致抛出此异常,我不知道为什么。帮忙

System.Drawing.dll中发生类型为“System.ArgumentException”的未处理异常

            using (Bitmap b = this.Document.Bitmap.Clone(new RectangleF() { Width = (int)this.croppingBorder.Width, Height = (int)this.croppingBorder.Height, X = (int)Canvas.GetLeft(this.croppingBorder), Y = (int)Canvas.GetTop(this.croppingBorder) }, this.Document.Bitmap.PixelFormat))
            {
                this.Document.Bitmap = b;
                BitmapSource bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(b.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
                image1.Source = bs;
            }

            canvas1.Width = this.Document.Bitmap.Width;
            canvas1.Height = this.Document.Bitmap.Height;

使用的
将处理位图。当您分配
this.Document.Bitmap=b时,您只是设置了一个引用。但是
using
语句结束并处理位图
b
,这是
this.Document.bitmap
引用的位图

我想你想要的是:

Bitmap b = this.Document.Bitmap.Clone(...);
this.Document.Bitmap.Dispose();
this.Document.Bitmap = b;

以下是您在处理发生的问题时所做的工作:

  • 您正在将原始位图克隆到
    b
  • 使用克隆覆盖
    Document.B
    ,但忘记处理旧值
  • 然后,当您使用
    块退出
    时,位图
    b
    也就是
    Document.b
    被释放,因此尝试获取该位图的尺寸失败
  • 此外,一旦复制了像素,就应该处理
    b.GetHBitmap()
通过使用“using”语句,您正在处理刚刚创建的位图对象。一旦您尝试访问它(例如,通过检索其宽度以分配给“canvas1.Width”),您将得到一个错误

相反,您可能应该将对原始位图的引用保存在一个临时变量中,将新位图实例分配给Document.Bitmap属性,然后显式地处理原始位图。所有这些都不使用“using”语句