How does one convert between System.Drawing.Icon开发者_运维知识库 type and byte[]? I'm looking for something simple that can (hopefully) work in .NET2.
You go via a MemoryStream, basically:
public static byte[] IconToBytes(Icon icon)
{
using (MemoryStream ms = new MemoryStream())
{
icon.Save(ms);
return ms.ToArray();
}
}
public static Icon BytesToIcon(byte[] bytes)
{
using (MemoryStream ms = new MemoryStream(bytes))
{
return new Icon(ms);
}
}
(Historical note: I wasn't sure whether or not it was safe to dispose of the stream passed to the constructor. It isn't safe to do so for Bitmap, for example... that holds on to the stream and may read from it later. Apparently it's okay for Icon though. I wish MSDN made this clearer...)
See: http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/1551fd3b-02b6-4479-852a-dfea4b610c35
Ex (there are multiple ways)
private byte[] GetBytes( Icon icon )
{
MemoryStream ms = new MemoryStream();
icon.Save( ms );
return ms.ToArray();
}
And:
Bitmap bmpIcon = icon.ToBitmap();
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
bmpIcon.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
return ms.ToArray();
}
... And back again
public static Icon IconFromBytes(byte[] bytes) {
using(var ms = new MemoryStream(bytes)) {
return new Icon(ms);
}
}
The Icon class reads from the stream as soon as it's constructed. No harm in closing MS.
加载中,请稍侯......
精彩评论