簡體   English   中英

C#在另一張圖上繪制位圖

[英]c# Drawing bitmap over another one

我正在一個項目上,我需要在一個已經存在的圖像(我在程序的開頭定義)中繪制從套接字接收的圖像塊(作為位圖),並將其顯示在PictureBox -換句話說,每次我收到一個新塊時都要更新圖像。

為了異步執行此操作,我使用了一個Thread ,該ThreadSocket讀取數據並進行處理。

這是我的代碼:

private void MainScreenThread() {

ReadData();
initial = bufferToJpeg(); //full screen first shot.
pictureBox1.Image = initial;

while (true) {
 int pos = ReadData();
 int x = BlockX();
 int y = BlockY();
 Bitmap block = bufferToJpeg(); //retrieveing the new block.

 Graphics g = Graphics.FromImage(initial);
 g.DrawImage(block, x, y); //drawing the new block over the inital image.
 this.Invoke(new Action(() => pictureBox1.Refresh())); //refreshing the picturebox-will update the intial;

 }
}
  private Bitmap bufferToJpeg()
    {
      return (Bitmap)Image.FromStream(ms);        
    }

我遇到錯誤

該對象當前在其他地方使用

Graphics創建行上

Graphics g = Graphics.FromImage(initial);

我沒有使用任何其他線程或其他東西來訪問位圖..所以我不確定這是什么問題。

如果有人能啟發我,我將非常感激。

謝謝。

嘗試在循環之前分配圖形:

private void MainScreenThread() {

  ReadData();
  initial = bufferToJpeg(); 
  pictureBox1.Image = initial;
  Graphics g = Graphics.FromImage(initial);

  while (true) {
    int pos = ReadData();
    int x = BlockX();
    int y = BlockY();
    Bitmap block = bufferToJpeg(); 

    g.DrawImage(block, x, y); 
    this.Invoke(new Action(() => pictureBox1.Refresh())); 

  }
}

這是因為您永遠不會在使用圖形對象后對其進行處置。

如果您查看圖形組件,則在創建時。 您使用“初始”位圖。 圖形現在指向該“初始”對象,第一次它將成功創建圖形,但是第二次(由於尚未釋放/釋放“ g”),“初始”對象仍在使用中。舊圖形,然后再創建新圖形。

您可以做的是:

private void MainScreenThread() {

   ReadData();
   initial = bufferToJpeg(); //full screen first shot.
   pictureBox1.Image = initial;

   while (true) {
    int pos = ReadData();
    int x = BlockX();
    int y = BlockY();
    Bitmap block = bufferToJpeg(); //retrieveing the new block.

    using(Graphics g = Graphics.FromImage(initial)) {
       g.DrawImage(block, x, y); //drawing the new block over the inital image.
       this.Invoke(new Action(() => pictureBox1.Refresh())); //refreshing the picturebox-will update the intial;
   }
 }
}

將會發生的情況是'g'對象在使用后將被處置,以便您以后可以再次執行相同的操作。

編輯 :修復-正確地將整個代碼作為代碼塊包括在內。

暫無
暫無

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

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