0

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

KansaiRobot
  • 7,564
  • 11
  • 71
  • 150
  • Do you perhaps try to overwrite the old image? This is only possible if you do not have any links to it open. So best open it in a using clause! Show us how you create or open the image! - Also: Why save it again if you just opened it? did you change it? How? – TaW Mar 14 '19 at 09:14
  • Please show us the exception too – "the famous CGi exception" tells me very little. – AKX Mar 14 '19 at 09:16
  • Ohhh famous for a limited amount of dev, I guess ? – Laurent Lequenne Mar 14 '19 at 09:41
  • The *the famous **GDI+** exception* is thrown when you try to save (or otherwise use) an Image that has been assigned to a Control directly from a file: the file is locked. One way to sever the stream is to Clone the Bitmap, before assigning it. Or *new()* it, assign the copy, dispose of the old Bitmap, dispose of the copy before assigning a new one. The method to use depends on the context where the Bitmap is used. PictureBox controls don't like Bitmaps assigned when Cloning in a `using` block. You'll need a copy of the Bitmap anyway. – Jimi Mar 14 '19 at 09:51

0 Answers0