Home >Backend Development >C++ >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:
MemoryStream
object to temporarily store the image data.Save
method of the Image
object to write the image to the MemoryStream
, preserving the original image format.ToArray
method of the MemoryStream
.Here's the C# code:
<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>
Converting Byte Arrays to Images
To reverse the process:
MemoryStream
and populate it with the byte array.Image.FromStream
method to generate an Image
object from the MemoryStream
.The C# code for this is:
<code class="language-csharp">public System.Drawing.Image ByteArrayToImage(byte[] byteArrayIn) { using (var ms = new MemoryStream(byteArrayIn)) { return Image.FromStream(ms); } }</code>
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!