Home >Backend Development >C++ >How to Convert Images to Byte Arrays and Back Again in C#?

How to Convert Images to Byte Arrays and Back Again in C#?

DDD
DDDOriginal
2025-01-26 03:21:17355browse

How to Convert Images to Byte Arrays and Back Again in C#?

Conversion between images and byte arrays in C#

Converting images to byte arrays and back is a common operation in many software applications. This conversion is especially useful when dealing with image storage, transfer, and processing.

Convert image to byte array

Convert the image to a byte array, you can follow the steps below:

  1. Create a MemoryStream object.
  2. Use the Save method to save the image to MemoryStream.
  3. Convert MemoryStream to byte array using ToArray method.

Code example:

<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>

Convert byte array to image

Convert byte array to image, you can follow these steps:

  1. Create a MemoryStream object and initialize it with a byte array.
  2. Create a Bitmap object from MemoryStream.

Code example:

<code class="language-csharp">public System.Drawing.Image ByteArrayToImage(byte[] imageByteArray)
{
   using (var ms = new MemoryStream(imageByteArray))
   {
      return System.Drawing.Image.FromStream(ms);
   }
}</code>

These conversion methods are essential for processing images in a variety of applications, such as saving images to databases, transferring images over the network, and performing image processing operations.

The above is the detailed content of How to Convert Images to Byte Arrays and Back Again 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