I believe that your problem is related to the type of image you are trying to save to the MemoryStream as. According to this Code Project article: Dynamically Generating Icons (safely), some of the ImageFormat types do not have the necessary encoder to allow the Save function to save as that type.
I ran the following to determine which types did and didn't work:
System.Drawing.Bitmap b = new Bitmap(10, 10);
foreach (ImageFormat format in new ImageFormat[]{
ImageFormat.Bmp,
ImageFormat.Emf,
ImageFormat.Exif,
ImageFormat.Gif,
ImageFormat.Icon,
ImageFormat.Jpeg,
ImageFormat.MemoryBmp,
ImageFormat.Png,
ImageFormat.Tiff,
ImageFormat.Wmf})
{
Console.Write("Trying {0}:", format);
MemoryStream ms = new MemoryStream();
bool success = true;
try
{
b.Save(ms, format);
}
catch (Exception)
{
success = false;
}
Console.WriteLine("{0}", (success ? "works" : "fails"));
}
This gave the results of:
Trying Bmp: works
Trying Emf: fails
Trying Exif: fails
Trying Gif: works
Trying Icon: fails
Trying Jpeg: works
Trying MemoryBMP: fails
Trying Png: works
Trying Tiff: works
Trying Wmf: fails
There is a Microsoft KB Article which states that some of the ImageFormat types are read-only.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…