Description
In this article, I am going to give C# code examples to Convert Image to Byte Array and Byte Array to Image using ImageConverter and MemoryStream.
Summary
- Convert Image File into Byte Array in C#
- Convert Image to Byte Array in C# using ImageConverter
- Convert Image to Byte Array in C# using MemoryStream
- Convert Byte Array to Image in C# using MemoryStream
- Convert Byte Array to Image File in C# using MemoryStream
Convert Image File into Byte Array in C#
public static byte[] ImageToByteArrayFromFilePath(string imagefilePath) { byte[] imageArray = File.ReadAllBytes(imagefilePath); return imageArray; }
Convert Image to Byte Array in C# using ImageConverter
Note: To use the classes ImageConverter and Image, you need to add the reference System.Drawing
public static byte[] ImageToByteArray(string imagefilePath) { System.Drawing.Image image = System.Drawing.Image.FromFile(imagefilePath); byte[] imageByte = ImageToByteArraybyImageConverter(image); return imageByte; } private static byte[] ImageToByteArraybyImageConverter(System.Drawing.Image image) { ImageConverter imageConverter = new ImageConverter(); byte[] imageByte = (byte[])imageConverter.ConvertTo(image, typeof(byte[])); return imageByte; }
Convert Image to Byte Array in C# using MemoryStream
Note: To use the classes ImageConverter and Image, you need to add the reference System.Drawing;
public static byte[] ImageToByteArray(string imagefilePath) { System.Drawing.Image image = System.Drawing.Image.FromFile(imagefilePath); byte[] imageByte = ImageToByteArraybyMemoryStream(image); return imageByte; } private static byte[] ImageToByteArraybyMemoryStream(Image image) { MemoryStream ms = new MemoryStream(); image.Save(ms, System.Drawing.Imaging.ImageFormat.Png); return ms.ToArray(); }
Convert Byte Array to Image in C# using MemoryStream
public static Image ByteArrayToImagebyMemoryStream(byte[] imageByte) { MemoryStream ms = new MemoryStream(imageByte); Image image = Image.FromStream(ms); return image; }
Convert Byte Array to Image File in C# using MemoryStream
public static void ByteArrayToImageFilebyMemoryStream(byte[] imageByte) { MemoryStream ms = new MemoryStream(imageByte); Image image = Image.FromStream(ms); image.Save(@"C:\UsersAdministratorDesktopimageTest.png"); }
Advertisement
thanks, it's very useful for me
Store image in database….Insert Image in Database
lig
Thank you. It's amazing how much code people write for something so simple.
I'm not a developer, I always use this free online image converter to convert image.