简体   繁体   中英

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?

You can try doing something like this. I have taken the name of the file and I'm asking if the file already exist and if it does, it adds number to the file name and it does in such a way that it keeps the file format. But if you don't want to save it with the file format you can do it without the fileName.Split(); just by adding the number behind the file name newFileName = fileName+$"_{i}"; . If this helped mark this as the answer.

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

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.

If this helped mark this as the answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM