I checked already for "duplicate questions". None of them have an answer to this question except maybe this one and that one is not working entirely in my case.
I want to simply save the image of a pictureBox to a file.
First I tried
if (picBoxImage.Image == null) return;
//Here we select to create a file
string fileName;
saveFileDialog1.Filter = "BMP (*.bmp)|*.bmp";
saveFileDialog1.FileName = "";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
fileName = saveFileDialog1.FileName;
}
else
{
return;
}
Trace.WriteLine(fileName);
picBoxImage.Image.Save(fileName, ImageFormat.Bmp);
This gave me an exception (the famous CGi exception)
So now I am trying and it works
using (Bitmap bitmap = new Bitmap(picBoxImage.Width, picBoxImage.Height))
{
using (Graphics graphics = Graphics.FromImage(bitmap))
{
graphics.Clear(Color.Transparent);
//graphics.DrawImage(picBoxImage.Image, (bitmap.Width - picBoxImage.Image.Width) / 2, (bitmap.Height - picBoxImage.Image.Height) / 2);
graphics.DrawImage(picBoxImage.Image, 0, 0,picBoxImage.Width,picBoxImage.Height);
}
bitmap.Save(fileName, ImageFormat.Bmp);
}
My question is why is the Save method of Image of PictureBox not working?? And why graphics is necessary