Home > Backend Development > C++ > How to Convert Images to Byte Arrays and Vice Versa in .NET?

How to Convert Images to Byte Arrays and Vice Versa in .NET?

Linda Hamilton
Release: 2025-01-26 03:41:16
Original
330 people have browsed it

How to Convert Images to Byte Arrays and Vice Versa in .NET?

Efficient Image Handling in .NET: Image-Byte Array Conversion

Working with images often requires converting between image formats and byte arrays. This is particularly useful in .NET applications, including WPF projects using stream readers. This guide provides a straightforward method for this conversion.

Converting Images to Byte Arrays

The process involves these steps:

  1. Initialize a MemoryStream object to temporarily store the image data.
  2. Utilize the Save method of the Image object to write the image to the MemoryStream, preserving the original image format.
  3. Extract the byte array using the ToArray method of the MemoryStream.

Here's the C# code:

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

Converting Byte Arrays to Images

To reverse the process:

  1. Create a MemoryStream and populate it with the byte array.
  2. Employ the Image.FromStream method to generate an Image object from the MemoryStream.

The C# code for this is:

public System.Drawing.Image ByteArrayToImage(byte[] byteArrayIn)
{
    using (var ms = new MemoryStream(byteArrayIn))
    {
        return Image.FromStream(ms);
    }
}
Copy after login

These methods provide a robust and efficient way to manage image data as byte arrays within your .NET applications. This is especially helpful when dealing with image storage, transmission, or manipulation within your WPF or other .NET projects.

The above is the detailed content of How to Convert Images to Byte Arrays and Vice Versa in .NET?. 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