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
Release: 2025-01-26 03:26:09
Original
371 people have browsed it

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>
Copy after login

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>
Copy after login

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 of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template