Converting Images to Byte Arrays and Back in C#
This article demonstrates how to efficiently convert images into byte arrays and vice-versa within a C# environment, focusing on methods suitable for WPF applications.
Method 1: Using MemoryStream
The ImageToByteArray
method leverages a MemoryStream
to capture the image data. The image is saved to the stream using its original format, and the resulting byte array is returned.
<code class="language-csharp">public byte[] ImageToByteArray(System.Drawing.Image imageIn) { using (var ms = new MemoryStream()) { imageIn.Save(ms, imageIn.RawFormat); return ms.ToArray(); } }</code>
Method 2: Direct Conversion with Image
Class
C# provides built-in functionality for streamlined image-to-byte array conversion:
<code class="language-csharp"> // Convert image to byte array byte[] imageArray = Image.FromFile("image.jpg").ToByteArray(); // Convert byte array to image Image convertedImage = Image.FromByteArray(imageArray); ``` This approach simplifies the process, eliminating the need for manual stream handling. Remember to handle potential exceptions (e.g., `FileNotFoundException`).</code>
The above is the detailed content of How to Convert an Image to a Byte Array and Back in C#?. For more information, please follow other related articles on the PHP Chinese website!