Search code examples
c#emgucv

Save images to folder using Emgu CV


I have a few images which are extracted from other images using Emgu CV.

I've tried to save these images into a folder, but only last image is being saved to folder with my code.

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

How I could save all images in one folder?


Solution

  • This answer is made for WinForms, but same principles should apply to to all the UI frameworks.

    If you want to be able to choose the folder in run time, then you can use this code:

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

    But keep in mind that this code will ask you for the folder every time that you are going to save the file. So if you are going to save multiple files at once, I would advise you to save the dirDialog.SelectedPath in some string variable.