使用Emgu CV将图像保存到文件夹

时间:2019-12-25 22:29:59

标签: c# emgucv

我有一些图像是使用Emgu CV从其他图像中提取的。

我尝试将这些图像保存到文件夹中,但是只有最后一张图像和我的代码一起保存到了文件夹中。

 Image.ToBitmap().save("filename",imageformat.png)

如何将所有图像保存在一个文件夹中?

2 个答案:

答案 0 :(得分:0)

您可以尝试执行以下操作。我已经取了文件的名称,然后询问文件是否已经存在,如果存在,它会在文件名中添加数字,并且这样做会保持文件格式。但是,如果您不想将其保存为文件格式,则只需添加文件名fileName.Split();后面的数字就可以在不使用newFileName = fileName+$"_{i}";的情况下进行保存。 如果这有助于将其标记为答案。

//if you want you can use this method or just copy the code you need
void Unique(Image input)
{
    string fileName = "filename.jpg";
    string newFilename = null;
    for(int i = 1; true; i++)

        //this is so that you can alter the name and keep the file format 
        newFileName = filename.Split('.')[0]+"_{i}"+filename.Split('.')[1];

        if(!File.Exist(newFileName))
        {   
            break;
        }
    }
    return Image.ToBitmap().Save(newFileName,ImageFormat.Png);
} 

答案 1 :(得分:0)

此答案适用于WinForms,但相同的原则应适用于所有UI框架。

如果您希望能够在运行时选择文件夹,则可以使用以下代码:

 void Unique(Image input)
    {
        string fileName = "filename.jpg";
        string newFileName = null;

        //Crates the dialog window
        var dirDialog = new FolderBrowserDialog();
        if (dirDialog.ShowDialog() == DialogResult.OK)
        {
            newFileName = dirDialog.SelectedPath + fileName;

            for (int i = 1; true; i++)
            {


                //this is so that you can alter the name and keep the file format 
                newFileName = fileName.Split('.')[0] + "_{i}" + fileName.Split('.')[1];

                if (!File.Exists(newFileName))
                {
                    break;
                }

            }
            //save the file
            new Bitmap(input).Save(newFileName, ImageFormat.Png);
        }

        //deletes the dialog window from memory
        dirDialog.Dispose();
    }

但是请紧记,该代码将在每次您要保存文件时询问您该文件夹。因此,如果您要一次保存多个文件,我建议您将dirDialog.SelectedPath保存在某些string变量中。

如果这有助于将其标记为答案。

相关问题