gpt4 book ai didi

c# - 秋天尝试更改图片框图像 c#

转载 作者:行者123 更新时间:2023-11-30 23:02:31 25 4
gpt4 key购买 nike

1. System.IO.File.Copy(fileName, Path.Combine(@"C:\images\", newFileName));

1 编译答案:

the process cannot access the file --- because it is being used by another process.

此文件在 pictureBox 中使用,我想更改 pictureBox 图像并将文件交换为新文件。

我找到了像这样使用 using 的答案:

using (pictureMain.Image = new Bitmap(newFileName))
{
// Do some stuff
}

但它不起作用,因为我需要图片始终可见..任何解决方案,我都会很高兴。谢谢

最佳答案

问题是一旦图片加载到 PictureBox 中,它就会保留文件的句柄。因此,为什么你不能复制它

要释放文件句柄,您需要Dispose()

// before copying the file make sure the file handle is released
// by calling dispose
if(PictureBox1.Image != null)
{
PictureBox1.Image.Dispose();
PictureBox1.Image = null;
}

...

// It should be safe to copy the file now, as the handle should be released
File.Copy(fileName, Path.Combine(@"C:\images\",newFileName));

但是,如果您想在尝试复制(我认为您正在尝试做的事情)时让图像保持事件状态(视觉显示),您基本上必须加载图像,然后以某种方式克隆它,然后释放 handle 。

所以我相信以下模式在加载图像时应该适合您

// before loading any new image lets release any previously displayed imaged
if(PictureBox1.Image != null)
{
PictureBox1.Image.Dispose();
PictureBox1.Image = null;
}

// this loads the image, copies it, then closes the handle
using (var bmpTemp = new Bitmap("image_file_path"))
{
PictureBox1.Image = new Bitmap(bmpTemp);
}

...

// It should be safe to copy the file now, as the handle should be released
File.Copy(fileName, Path.Combine(@"C:\images\", newFileName));

Final note: After you have finished with the image, make sure you dispose it. I.e if you create it, it needs to be disposed.

关于c# - 秋天尝试更改图片框图像 c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50439852/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com