1

Essentially, I need to create a new bitmap from an existing one (this.Document.Bitmap) and then replace that existing one with the new one in the same property. I also would prefer to dispose of any extra memory this clone may cause, but am getting this error.

The statements outside of the using block are causing this exception to be thrown and I can't figure out why. Help?

An unhandled exception of type 'System.ArgumentException' occurred in System.Drawing.dll.

            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;
0

3 Answers 3

2

The using disposes of the bitmap. When you assign this.Document.Bitmap = b;, you're just setting a reference. But then the using statement ends and disposes of the bitmap b, which is the bitmap that's referenced by this.Document.Bitmap.

I think what you want is:

Bitmap b = this.Document.Bitmap.Clone(...);
this.Document.Bitmap.Dispose();
this.Document.Bitmap = b;
Sign up to request clarification or add additional context in comments.

Comments

1

By using the "using" statement, you are disposing the Bitmap object you just created. As soon as you try to access it (e.g. by retrieving its Width for assignment to "canvas1.Width"), you'll get an error.

Instead, you should probably be saving the reference to the original Bitmap in a temporary variable, assigning the new Bitmap instance to the Document.Bitmap property, and then explicitly disposing the original Bitmap. All without the use of the "using" statement.

Comments

0

Here's what you're doing along the issues happening:

  • you are cloning original bitmap to b
  • you overwrite Document.B with the clone but forget to dispose the old value
  • then when you exit using block, the bitmap b which is also Document.B is disposed, therefore trying to get dimensions of that bitmap fails.
  • additionally, you should dispose b.GetHBitmap() once you have copied the pixels.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.