Home
Manage Your Code
Snippet: Convert Image to Byte Array (C#)
Title: Convert Image to Byte Array Language: C#
Description: Convert an image object to a byte array in a specified format. Views: 190
Author: Matt Schmidt Date Added: 8/15/2008
Copy Code  
1        /// <summary>
2        /// Converts a System.Drawing.Image to a 1-dimensional byte array.
3        /// </summary>
4        /// <param name="imageToConvert">Image to convert</param>
5        /// <param name="formatOfImage">Image format</param>
6        /// <returns>Byte array representation of image</returns>
7        private byte[] ConvertImageToByteArray(System.Drawing.Image imageToConvert, ImageFormat formatOfImage)
8        {
9            try
10            {
11                byte[] Ret;
12
13                using (MemoryStream ms = new MemoryStream())
14                {
15                    imageToConvert.Save(ms, formatOfImage);
16                    Ret = ms.ToArray();
17                }
18                return Ret;
19            }
20            catch (Exception ex) 
21            {
22      		//handle exception
23                return new byte[0]; 
24            }
25        }