Menü Schließen

Convert Image to Byte Array (and back)

The following functions can be used to convert an image object to a byte array (and vise versa).

This is often used to store images in a database or file or to use them in a stream.

/// <summary>
/// Converts an image to a byte array.
/// </summary>
/// <param name="image">The image.</param>
/// <returns>Byte array</returns>
public static byte[] ImageToByteArray(Image image)
{
  if (image == null)
    return Array.Empty<byte>();

  using (MemoryStream stream = new MemoryStream())
  {
    image.Save(stream, ImageFormat.Jpeg);
    return stream.ToArray();
  }
}

/// <summary>
/// Converts a byte array to an image.
/// </summary>
/// <param name="buffer">The buffer.</param>
/// <returns>Image</returns>
public static Image ByteArrayToImage(byte[] buffer)
{
  if (buffer == null)
    return new Bitmap(10, 10);

  using (MemoryStream stream = new MemoryStream(buffer))
  {
    Image img = Image.FromStream(stream);
    return img;
  }
}

 

Ähnliche Beiträge

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert