I write commands for working with the file menu. There was a problem: if I open an image, and then try to save it, the ExternalException error crashes. It is written about it on msdn, which occurs if:
1) The image was saved in the wrong format.
2) The image is saved to the same file from which it was created.
How then to overwrite the file in this case? So far only such an idea has come: to create an additional file with a different name, to save the image there. Next - delete the first image, and then rename the new file to the old name. But it is hemorrhoids.
Does anyone know how this can be implemented normally? I throw off the code below when the error crashes:
public Form1() { //InitializeComponent(); Size = new Size(1000, 1000); var bitmap = new Bitmap(1, 1); var fullExistFileName = ""; var pictureBox = new PictureBox() { Parent = this, BackColor = SystemColors.ControlLightLight, Size = new Size(800, 800), Location = new Point(50, 50) }; var buttonToOpen = new Button { Parent = this, BackColor = SystemColors.Control, Size = new Size(70, 20), Location = new Point(60, 20), Text = "Открыть" }; var buttonToSave = new Button { Parent = this, BackColor = SystemColors.Control, Enabled = false, Size = new Size(70, 20), Location = new Point(140, 20), Text = "Сохранить" }; buttonToOpen.Click += (o, e) => { var openFileDialog = new OpenFileDialog(); openFileDialog.Filter = "Все файлы изображений(*.BMP;*.PNG;*.JPEG;*.GIF)|*.BMP;*.PNG;*.JPG;*.GIF|PNG|*.png|JPEG|*.jpg;*.jpeg;*.jpe;*.jfif|GIF|*.gif"; if (openFileDialog.ShowDialog() == DialogResult.OK) { bitmap = new Bitmap(openFileDialog.FileName); fullExistFileName = openFileDialog.FileName; } buttonToSave.Enabled = true; pictureBox.Invalidate(); }; buttonToSave.Click += (o, e) => { var saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "PNG|*.png|JPEG|*.jpg;*.jpeg;*.jpe;*.jfif|BMP|*.bmp|GIF|*.gif"; saveFileDialog.FileName = fullExistFileName; if (saveFileDialog.ShowDialog() == DialogResult.OK) { var newBitmap = new Bitmap(pictureBox.Width, pictureBox.Height); pictureBox.DrawToBitmap(newBitmap, pictureBox.ClientRectangle); newBitmap.Save(saveFileDialog.FileName); } }; pictureBox.Paint += (o, e) => { e.Graphics.DrawImage(bitmap, 0, 0); }; }