Home >Backend Development >C++ >How to Convert an Image to a Byte Array and Back in C#?

How to Convert an Image to a Byte Array and Back in C#?

Linda Hamilton
Linda HamiltonOriginal
2025-01-26 03:26:09400browse

How to Convert an Image to a Byte Array and Back in C#?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn