c# 在另一个位图上绘制位图

本文关键字:位图 绘制 另一个 | 更新日期: 2023-09-27 17:55:39

我正在做一个项目,我需要绘制我从已经存在的图像上的套接字接收的图像块(作为位图)(我在程序开头定义),并将其显示在PictureBox上 - 换句话说,每次我收到新块时都会更新图像。

为了异步执行此操作,我使用了一个从Socket读取数据并对其进行处理的Thread

这是我的代码:

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

我没有使用任何其他线程或访问位图的东西。所以我不确定这里有什么问题..

如果有人能启发我,我将不胜感激。

谢谢。

c# 在另一个位图上绘制位图

尝试在循环之前指定图形:

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"对象在使用后将被释放,以便之后可以再次执行相同的操作。

编辑:修复 - 未正确包含整个代码作为代码块。