Why is Image.Save(Stream, ImageFormat) throwing an exception?
Asked Answered
H

2

6

I am trying to convert an image to an icon. My function is:

private Icon GenerateIcon(int width, int height)
{
    using (Bitmap icon = _backingImage.GetThumbnailImage(width, height, () => false, System.IntPtr.Zero) as Bitmap)
    using(MemoryStream imgStream = new MemoryStream())
    {
        icon.Save(imgStream, System.Drawing.Imaging.ImageFormat.Icon);
        return new Icon(imgStream);
    }
}

But when the programme calls the method, it throws an ArgumentNullException("encoder") where I'm calling icon.Save.

I find this odd because I'm not passing in an encoder, I want the framework to figure out what the encoder should be, which is why I'm passing in an ImageFormat.

Is it that there aren't any encoders for ImageFormat.Icon, or is there something I'm doing wrong?

Heretic answered 13/11, 2010 at 10:47 Comment(0)
D
5

You guessed it right: GDI+ only supports an ICON decoder.

You might want to perform the conversion yourself. In that case, see http://www.codeproject.com/KB/GDI-plus/safeicon.aspx.

Divide answered 13/11, 2010 at 10:59 Comment(0)
B
5

Just convert image to icon:

Icon myIcon = Icon.FromHandle(((Bitmap)myImage).GetHicon())

and then save it using stream:

myIcon.Save(myStream);

regards, Kate

Burned answered 24/1, 2011 at 14:29 Comment(1)
Thanks, SmartK8. I am aware of that, however it doesn't work in partial trust scenarios.Heretic

© 2022 - 2024 — McMap. All rights reserved.