Reputation: 5
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?
Upvotes: 0
Views: 2988
Reputation: 108
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 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);
}
Upvotes: 1
Reputation: 108
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.
Upvotes: 1