Question

I'm trying to export an image of an MSChart.

I have found the wonderful function

[System.Windows.Forms.DataVisualization.Charting.Chart.SaveImage][1]

However I'm having a few problems with the ImageFormat parameter. Specifically I wish the user to be able to save the image in any format that they have a WIC encoder for. To this end I get a list of the Image codecs and provide them all to the user.

As such when the user has selected their file I grab the extension and find the codec in the list that matches the extension. I then create the relevant ImageFormat as follows:

ImageFormat imgFmt  = new ImageFormat( codec.FormatID );

I then call the following to export the chart:

exportChart.SaveImage( mSaveFileDialog.FileName, imgFmt );

However this throws an exception, if I selected EMF or WMF, as follows:

A first chance exception of type 'System.ArgumentNullException' occurred in System.Drawing.dll
An unhandled exception of type 'System.ArgumentNullException' occurred in System.Drawing.dll

Additional information: Value cannot be null.

The oddest thing is that if I create my Image format as follows:

ImageFormat imgFmt = ImageFormat.Emf;

then it writes an EMF with no problems. Furthermore if I do (with the original imgFmt):

imgFmt.Equals( ImageFormat.Emf )

Then it returns true but still throws the exception.

Has anybody got any idea why this is happening and have a solution to my issues?

Was it helpful?

Solution

I think internally the charting control uses the ImageFormat you provide to select an ImageCodecInfo. This exception is thrown because said codec info cannot be found.

ImageFormat fmt = ImageFormat.Emf;
ImageFormat fmt2 = new ImageFormat(ImageFormat.Emf.Guid);
Console.WriteLine(fmt.ToString()); // gives: Emf
Console.WriteLine(fmt2.ToString()); // gives: [ImageFormat: b96b3cac-0728-11d3-9d7b-0000f81ef32e]

If you call ToString() on the two formats, you'll see that they do not return the same thing. It is quite possible the code to select the encoder did not anticipate ImageFormat constructed from GUID and simply looks for a list of known format names.

Looking into the mschart samples, the preferred argument type for this function is the enum ChartImageFormat, not Imageformat.

This does not solve your problem, but hopefully makes it less mysterious.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top