Save Image to Byte Array

Saving an Image object to disk is straight forward, just call the Image.Save(filname) method and it's done. But what if you need to save that Image to a Byte() array (or Byte[] in c# speak ;) because you need to store it in a database or stream it somewhere? It turned out to be quite simple if you use the MemoryStream class of .NET and the Image.Save(stream, imagetype) method overload:
 
Dim img As Image = LoadImageSomehow()
Dim rawData() AsByte
Using ms AsNew MemoryStream()
   img.Save(ms, Imaging.ImageFormat.Png)
   rawData = ms.GetBuffer()
EndUsing
'do something with the rawData buffer here...
 
Works for me.
 

No Comments