如何将图像表单目录加载到pictureBox,然后在加载到图片框并再次加载到下一个图像后删除图像文件


int countimages = 0;
        private void timer1_Tick(object sender, EventArgs e)
        {           
            Image img = sc.CaptureWindowToMemory(windowHandle);
            Bitmap bmp = new Bitmap(img,img.Width,img.Height);
            bmp.Save(@"e:screenshotsofpicturebox1screenshot" + countimages + ".bmp");
            bmp.Dispose();
            string[] images = Directory.GetFiles(@"e:screenshotsofpicturebox1", "*.bmp");
            if (images.Length > 0)
            {
                if (pictureBox1.Image != null)
                {
                    File.Delete(images[0]);
                    countimages = 0;
                    pictureBox1.Image.Dispose();
                }
                pictureBox1.Image = Image.FromFile(images[countimages]);
            }
            countimages += 1;
            label1.Text = countimages.ToString();
        }
  1. 我想将图像保存到硬盘
  2. 将图像加载到图片框1
  3. 将图像加载到图片盒1后,从硬盘中删除文件
  4. 将新图像保存到硬盘并将其加载到图片框中1
  5. 每次使用新图像删除文件等。

现在的问题是我在线遇到异常:

File.Delete(images[0]);

该进程无法访问该文件e:screenshotsofpicturebox1screenshot0.bmp因为它正由另一个进程使用。

我现在看到的另一个问题是每次将新文件保存到硬盘时都会保存

screenshot0.bmp
screenshot1.bmp

但是我希望每次screenshot0.bmp都只有一个文件,每次都用新图像替换它。

阅读您的代码,我假设您正在尝试在每个tick事件的图片框中显示屏幕。因此,如果这是您的目标,则无需保存/删除它,只需将 Image 对象分配给 PictureBox Image 属性,如下所示:

private void timer1_Tick(object sender, EventArgs e) {
    Image refToDispose = pictureBox1.Image;
    pictureBox1.Image = sc.CaptureWindowToMemory(windowHandle);
    refToDispose.Dispose();
}

如果仍然要保存/删除它,则无法将直接加载的位图从文件传递到 PictureBox,因为它会在使用时锁定文件。

相反,您可以从另一个具有图像大小的位图实例创建图形对象并对其进行绘制,因此新的位图将是一个没有文件锁定的副本,您可以将其分配给 PictureBox。

在您的代码中更改以下内容:

pictureBox1.Image = Image.FromFile(images[countimages]);

对此:

using (Image imgFromFile = Image.FromFile(images[countimages])) {
    Bitmap bmp = new Bitmap(imgFromFile.Width, imgFromFile.Height);
    using (Graphics g = Graphics.FromImage(bmp)) {
        g.DrawImage(imgFromFile, new Point(0, 0));
    }
    pictureBox1.Image = bmp;
}

最新更新