0

I use the following code for output of my calculations which it should be a PNG picture. I do not understand why in Debug run the last line gives me a System.Runtime.InteropServices.ExternalException. On the Release run everything is OK.

I found on the net that this error may occur when the image is being used by other part of code, but in my case it is not true.

//using System;
//using System.Drawing;
//using System.Drawing.Imaging;

Bitmap png = new Bitmap(this.xPixels, this.yPixels, PixelFormat.Format32bppArgb);
Graphics g = Graphics.FromImage(png);
g.Clear(Color.White);
g.DrawString(currentTime, myFont, mySolidBrush, timeX, timeY, myXTitleFormat);

// write image to file
string path4 = string.Concat(Environment.CurrentDirectory, @"\Output\T1\" + this.fileName + ".png");
png.Save(path4, ImageFormat.Png);
stakx - no longer contributing
  • 83,039
  • 20
  • 168
  • 268
Mehdi
  • 211
  • 2
  • 11
  • can you just check whether you have permission to write files to the specified folder? – daryal Aug 06 '14 at 07:11
  • Have you tried to change the path to be the same in debug/release, say "C:\test.png"? – Onur Aug 06 '14 at 07:20
  • @Onur: actually, the output folder is in my release folder. Can it cause this error ? – Mehdi Aug 06 '14 at 07:22
  • I'd remove as much differences between debug/release as possible and would try to hard-code as much as possible (like the path). – Onur Aug 06 '14 at 07:42
  • 2
    **Never** use Environment.CurrentDirectory in your code. The odds that it is not the directory that you hope it is are far too great. Kaboom when there is no "\Output\T1\" subdirectory. Multiplied by the odds of not having write access, like any of the c:\program files subdirectories. Use AppData instead. – Hans Passant Aug 06 '14 at 09:17
  • Thank you @HansPassant. Was going crazy thinking it was something image related. I'm no expert but I can't imagine it would have been too difficult to make these error messages a bit more helpful! 'Invalid Path'. job done – Mike T Dec 08 '15 at 02:29

1 Answers1

0

The online help says that "The image was saved with the wrong image format".

It's also strange that you do stuff with the Graphics object, but save using the Bitmap. Do the operations made with g influence the Bitmap?

The following code raises the exception whether in debug or release mode:

       {

            Bitmap png = new Bitmap(100, 100, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            Graphics g = Graphics.FromImage(png);
            g.Clear(Color.White);
            g.DrawString("dummy", SystemFonts.DefaultFont, Brushes.Beige, RectangleF.FromLTRB(5,5,80,80), StringFormat.GenericDefault);

            // write image to file
            string path4 = @"C:\test.png";

            png.Save(path4, System.Drawing.Imaging.ImageFormat.Png);

        }
Onur
  • 5,017
  • 5
  • 38
  • 54