How to convert image to byte array

Can anyone tell me how I can convert an image to a byte array and vice versa?

If anyone has some code examples to help me, that would be great.

I am developing a WPF application and using a streaming reader.

+96
c # wpf
Sep 27 '10 at 5:17
source share
11 answers

Sample code to convert an image to a byte array

public byte[] ImageToByteArray(System.Drawing.Image imageIn) { using (var ms = new MemoryStream()) { imageIn.Save(ms,imageIn.RawFormat); return ms.ToArray(); } } 

C # Image to byte array and byte array to image converter class

+130
Sep 27 '10 at 5:20
source share

To convert an image object to byte[] you can do the following:

 public static byte[] converterDemo(Image x) { ImageConverter _imageConverter = new ImageConverter(); byte[] xByte = (byte[])_imageConverter.ConvertTo(x, typeof(byte[])); return xByte; } 
+46
Jun 06 '13 at 9:14
source share

Another way to get an array of bytes from the image path is

 byte[] imgdata = System.IO.File.ReadAllBytes(HttpContext.Current.Server.MapPath(path)); 
+27
May 11 '12 at 5:45
source share

try the following:

 public byte[] imageToByteArray(System.Drawing.Image imageIn) { MemoryStream ms = new MemoryStream(); imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif); return ms.ToArray(); } public Image byteArrayToImage(byte[] byteArrayIn) { MemoryStream ms = new MemoryStream(byteArrayIn); Image returnImage = Image.FromStream(ms); return returnImage; } 
+16
Sep 27 '10 at 5:22
source share

You can use the File.ReadAllBytes() method to read any file into a byte array. To write an array of bytes to a file, simply use the File.WriteAllBytes() method.

Hope this helps.

You can find more information and sample code here .

+14
Sep 27 '10 at 5:23
source share

Here is what I am using now. Some of the other methods I tried were not optimal because they changed the pixel bit depth (24-bit or 32-bit) or ignored the image resolution (dpi).

  // ImageConverter object used to convert byte arrays containing JPEG or PNG file images into // Bitmap objects. This is static and only gets instantiated once. private static readonly ImageConverter _imageConverter = new ImageConverter(); 

Image to byte array:

  /// <summary> /// Method to "convert" an Image object into a byte array, formatted in PNG file format, which /// provides lossless compression. This can be used together with the GetImageFromByteArray() /// method to provide a kind of serialization / deserialization. /// </summary> /// <param name="theImage">Image object, must be convertable to PNG format</param> /// <returns>byte array image of a PNG file containing the image</returns> public static byte[] CopyImageToByteArray(Image theImage) { using (MemoryStream memoryStream = new MemoryStream()) { theImage.Save(memoryStream, ImageFormat.Png); return memoryStream.ToArray(); } } 

Array byte for image:

  /// <summary> /// Method that uses the ImageConverter object in .Net Framework to convert a byte array, /// presumably containing a JPEG or PNG file image, into a Bitmap object, which can also be /// used as an Image object. /// </summary> /// <param name="byteArray">byte array containing JPEG or PNG file image or similar</param> /// <returns>Bitmap object if it works, else exception is thrown</returns> public static Bitmap GetImageFromByteArray(byte[] byteArray) { Bitmap bm = (Bitmap)_imageConverter.ConvertFrom(byteArray); if (bm != null && (bm.HorizontalResolution != (int)bm.HorizontalResolution || bm.VerticalResolution != (int)bm.VerticalResolution)) { // Correct a strange glitch that has been observed in the test program when converting // from a PNG file image created by CopyImageToByteArray() - the dpi value "drifts" // slightly away from the nominal integer value bm.SetResolution((int)(bm.HorizontalResolution + 0.5f), (int)(bm.VerticalResolution + 0.5f)); } return bm; } 

Edit: To retrieve an image from a jpg or png file, you must read the file into an array of bytes using File.ReadAllBytes ():

  Bitmap newBitmap = GetImageFromByteArray(File.ReadAllBytes(fileName)); 

This avoids Bitmap-related issues that want its source stream to be open, and some suggested workarounds for this issue that lock the source file.

+14
May 15 '13 at 23:11
source share

Do you want pixels or the whole image (including headers) as a byte array?

For pixels: use the CopyPixels method in the bitmap. Something like:

 var bitmap = new BitmapImage(uri); //Pixel array byte[] pixels = new byte[width * height * 4]; //account for stride if necessary and whether the image is 32 bit, 16 bit etc. bitmap.CopyPixels(..size, pixels, fullStride, 0); 
+5
Sep 27 '10 at 5:20
source share

If you do not reference imageBytes for transferring bytes in a stream, the method will not return anything. Make sure you reference the image Bytes = m.ToArray ();

  public static byte[] SerializeImage() { MemoryStream m; string PicPath = pathToImage"; byte[] imageBytes; using (Image image = Image.FromFile(PicPath)) { using ( m = new MemoryStream()) { image.Save(m, image.RawFormat); imageBytes = new byte[m.Length]; //Very Important imageBytes = m.ToArray(); }//end using }//end using return imageBytes; }//SerializeImage 
+3
May 9 '17 at 14:53
source share

the code:

 using System.IO; byte[] img = File.ReadAllBytes(openFileDialog1.FileName); 
+2
Jan 08 '17 at 21:23
source share

This is the code to convert any type of image (e.g. PNG, JPG, JPEG) to a byte array.

 public static byte[] imageConversion(string imageName){ //Initialize a file stream to read the image file FileStream fs = new FileStream(imageName, FileMode.Open, FileAccess.Read); //Initialize a byte array with size of stream byte[] imgByteArr = new byte[fs.Length]; //Read data from the file stream and put into the byte array fs.Read(imgByteArr, 0, Convert.ToInt32(fs.Length)); //Close a file stream fs.Close(); return imageByteArr } 
0
Jun 22 '19 at 12:37
source share

This code retrieves the first 100 rows from a table in SQLSERVER 2012 and saves the image in a row as a file on the local disk

  public void SavePicture() { SqlConnection con = new SqlConnection("Data Source=localhost;Integrated security=true;database=databasename"); SqlDataAdapter da = new SqlDataAdapter("select top 100 [Name] ,[Picture] From tablename", con); SqlCommandBuilder MyCB = new SqlCommandBuilder(da); DataSet ds = new DataSet("tablename"); byte[] MyData = new byte[0]; da.Fill(ds, "tablename"); DataTable table = ds.Tables["tablename"]; for (int i = 0; i < table.Rows.Count;i++ ) { DataRow myRow; myRow = ds.Tables["tablename"].Rows[i]; MyData = (byte[])myRow["Picture"]; int ArraySize = new int(); ArraySize = MyData.GetUpperBound(0); FileStream fs = new FileStream(@"C:\NewFolder\" + myRow["Name"].ToString() + ".jpg", FileMode.OpenOrCreate, FileAccess.Write); fs.Write(MyData, 0, ArraySize); fs.Close(); } } 

note: a directory named NewFolder must exist in C: \

-2
Jun 01 '15 at 8:25
source share



All Articles