Thursday, October 28, 2010

Save Image to Byte Array

To convert an image to a byte array in C#, we first save the image to a stream and then copy the contents of this stream to a byte array.
In general, every stream can be used for that, the easiest one will probably be to use a MemoryStream, which simply writes data temporarily in the RAM or reads from it.
An image can be written by the function Save() in the as parameter specified value, as second parameter  the desired format is passed over, in which the bitmap is to be saved. (so e.g. Gif or Bmp).
The following sample code saves the content of the pictureBox on the form in a byte array:

            MemoryStream TempStream = new MemoryStream();
            byte[] ImageInBytes;

            pictureBox1.Image.Save(TempStream, System.Drawing.Imaging.ImageFormat.Gif);
            ImageInBytes = TempStream.ToArray();

No comments:

Post a Comment