Dynamically loading an Icon into an ImageList from a Stream

G

Guest

I'm having a problem loading an Icon into an ImageList.

When I load the icon directly it works fine, like this:


Icon sourceIcon = << Get an icon from somewhere... >>;
treeViewImageList.Images.Add("abc", sourceIcon);


But when I first save the original icon to a stream and then try loading the
ImageList from the stream, the icon image is messed up. Here's that code:


Icon sourceIcon = << Get an icon from somewhere... >>;
MemoryStream imageStream = new MemoryStream();
sourceIcon.Save(imageStream);
imageStream.Position = 0;
Icon icon = new Icon(imageStream);
treeViewImageList.Images.Add("abc", icon);


The ultimate goal is to use the stream to save the icon byte array to a
database and then load it again later but first I need to be able to get the
icon to reload correctly from the stream.

Any ideas what I'm doing wrong here?

Thanks.

- Adam
 
M

Marc Gravell

The following works absolutely fine for me. Are you by any chance
doing something funny with the ImageList.ImageSize? Scaling will make
them look terrible...

Marc

static void Main()
{
Application.EnableVisualStyles();
// tray1 is a random icon in a resx
Icon ico1 = Resource1.tray1, ico2;
using(MemoryStream ms = new MemoryStream()) {
ico1.Save(ms);
ms.Position = 0;
ico2 = new Icon(ms);
}
// show the 2 icons on a treeview
using(Form f = new Form())
using(ImageList il = new ImageList())
using(TreeView tv = new TreeView()) {
il.Images.Add("ico1", ico1);
il.Images.Add("ico2", ico2);
tv.ImageList = il;
tv.Dock = DockStyle.Fill;
tv.Nodes.Add("node1", "Original", "ico1");
tv.Nodes.Add("node2", "Saved", "ico2");
tv.ExpandAll();
f.Controls.Add(tv);
f.ShowDialog();
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top