簡體   English   中英

C#/ WPF - 使用Bitmap / SystemArgumentException錯誤

[英]C#/WPF - Using Bitmap/SystemArgumentException Error

本質上,我需要從現有的位圖(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;

using處理位圖。 當你賦值this.Document.Bitmap = b; ,你只是設置一個參考。 但是然后using語句結束並處理位圖b ,這是this.Document.Bitmap引用的位圖。

我想你想要的是:

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

通過使用“using”語句,您將處置剛剛創建的Bitmap對象。 一旦您嘗試訪問它(例如,通過檢索其寬度以分配給“canvas1.Width”),您將收到錯誤。

相反,您可能應該在臨時變量中保存對原始位圖的引用,將新的Bitmap實例分配給Document.Bitmap屬性,然后顯式處理原始位圖。 所有這些都沒有使用“使用”聲明。

以下是您在發生問題時所做的工作:

  • 你正在將原始位圖克隆到b
  • 您使用克隆覆蓋Document.B但忘記處置舊值
  • 然后當你using塊退出時,也會放置也是Document.B的位圖b ,因此嘗試獲取該位圖的尺寸失敗。
  • 另外,一旦復制了像素,就應該處理b.GetHBitmap()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM