【问题标题】:Editting the picturebox image using external editor and loading the new image使用外部编辑器编辑图片框图像并加载新图像
【发布时间】:2017-11-20 08:04:45
【问题描述】:

我尝试在运行时打开外部编辑器并编辑当前设置为PictureBox 的图像,编辑图像并在关闭编辑器后更新图像。
为此,我有一个简单的 c# windows 应用程序,其中有一个 PictureBox 和两个 Button 一个用于从文件加载 PictureBox 图像,另一个用于使用 MS Paint 编辑图像。
代码如下:

public partial class Form1 : Form
{
    string myImagePath = @"C:\temp\bt_logo.png";
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        pictureBox1.Image = Image.FromFile(myImagePath);
    }

    private void button2_Click(object sender, EventArgs e)
    {
        System.Diagnostics.ProcessStartInfo launchEditor = new System.Diagnostics.ProcessStartInfo();
        launchEditor.FileName = "mspaint";
        launchEditor.Arguments = myImagePath;
        launchEditor.UseShellExecute = true;
        System.Diagnostics.Process.Start(launchEditor);
    }
}

编辑器打开成功,但由于访问问题无法保存更改:

知道如何解决这个问题吗?

EDIT1:
为了在编辑器打开时停止访问图片,我修改了button2_Click()的代码如下:

pictureBox1.Image = null;
System.Diagnostics.ProcessStartInfo launchEditor = new System.Diagnostics.ProcessStartInfo();
launchEditor.FileName = "mspaint";
launchEditor.Arguments = myImagePath;
launchEditor.UseShellExecute = true;
System.Diagnostics.Process.Start(launchEditor);
pictureBox1.Image = Image.FromFile(myImagePath);

同样的结果。作为另一次尝试,我制作了图像的副本,对其进行了修改并将其复制到原始图像中,

System.IO.File.Copy(myImagePath, myImagePath_temp, true);
System.Diagnostics.ProcessStartInfo launchEditor = new System.Diagnostics.ProcessStartInfo();
launchEditor.FileName = "mspaint";
launchEditor.Arguments = myImagePath_temp;
launchEditor.UseShellExecute = true;
System.Diagnostics.Process.Start(launchEditor);
System.IO.File.Copy(myImagePath_temp, myImagePath, true);

同样的结果!

【问题讨论】:

  • 也许将图像的临时副本加载到图片框中,并在将其保存在 Paint 中后将其替换为更新的图像?
  • Ian 这是因为 image.fromfile 会锁定文件,直到 image 变量被释放
  • @Caius:但修改Edit1后,它仍然无法正常工作
  • 对于您在 Edit1 中的第一次尝试,很可能 mspaint 仍在加载,并且在您的程序运行 pictureBox1.Image = Image.FromFile(myImagePath) 时尚未尝试加载图像。为什么第二次尝试失败对我来说是一个谜。

标签: c# access-denied


【解决方案1】:

这个问题本质上是重复的

Open Image from file, then release lock?

Image.FromFile 将文件锁定在磁盘上,直到代码中的 image 变量被释放。您应该遵守上述问题的公认答案;它提供了一种从磁盘加载图像数据,将其复制到程序内存中,然后释放文件锁定并使用图片框中位图数据副本的方法

您将找到有关如何加载图像而不将其锁定在文件系统中的答案。我正在写一个答案而不是评论,因为我想给程序的其余部分提供一些进一步的建议

看一下 FileSystemWatcher 类; Notification when a file changes?

您可以使用它来检测文件的更改,以便在保存文件而不是退出绘制时更新图片框 - 这比编码检测应用程序关闭更容易

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-05
    • 1970-01-01
    • 2013-01-06
    • 2018-10-23
    • 2011-03-10
    • 1970-01-01
    • 2016-07-31
    • 2011-08-22
    相关资源
    最近更新 更多